I have been trying this for hours now - and I can't seem to find any posts that work. I am adding custom php classes to the Symfony2 vendor directory.
For example (copied other vendor structure):
vendor/mylib/mylib/src/Mylib/Lib/Class.php
I then updated the root composer.json by adding:
"require": {
"mylib/mylib": "@dev"
},
I also created a composer.json in vendor/mylib/mylib which contained:
{
"name": "mylib/mylib",
"type": "library",
"description": "My Libraty",
"keywords": ["library"],
"autoload": {
"psr-0": { "Mylib\\": "src/" }
},
"minimum-stability": "dev"
}
I have added a namespace in Class.php:
namespace MyLib\Lib;
In one of my bundles I have added the below:
use MyLib\Lib\ClassName as ClassName;
class Cms extends ClassName
{}
The error I am getting is:
FatalErrorException: Error: Class 'MyLib\Lib\MyClass' not found in C:\xampp\htdocs\My_CMS\src\Cms\CmsBundle\Entity\Cms.php line 13
What am I doing wrong?
You really should be using service containers which is basically the symfony way to load classes.
Here's why:
http://symfony.com/doc/current/book/service_container.html
A Service Container (or dependency injection container) is simply a PHP object that manages the instantiation of services (i.e. objects).
So basically symfony will handle instantiation of classes for you in your controller. All you need to do is the following:
Add a folder under your path called Libraries --> src/AppBundle/Libraries
Add the class to this folder with a namespace at the top. My example is:
<?php
namespace AppBundle\Libraries;
class MyRecommendations{
public function __construct(){
}
public function init(){
die("init");
}
}
Then add a file called services.yml to your app. app/config/services.yml
Put the following code in it do not use tabbing in the yml file
services:
myrecommendations:
class: AppBundle\Libraries\MyRecommendations
#arguments: [specialparamhere] #constructor parameters here
Then add the third line resources: services.yml to your config.yml file.
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
At the top of your controller when using just add the use statement
use AppBundle\Libraries\MyRecommendations;
Now call your code
$test = $this->get('myrecommendations');
$test->init();
echo's out
init
In php classes are autoloaded via __autoload
Symfony takes care about it in it's Class Loader but in fact it works the same way. There is no background scaning all directories so you have to add your namespace manually.
You need to add in your autoload.php file:
$loader->add('NAMESPACE','/path/to/vendor');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With