I play around with Silex, PHP micro-framework. At the moment I try to load my own classes but I have no luck doing it. Maybe somebody could explain me a little how does loading in Silex works?
My project structure looks like this:
app/
vendor/
web/
tests/
bootstrap.php
composer.json
composer.lock
Let's say I want to load a class Controller\User (namespace here)
from /app/MainController.php
.
How can I do that? I've browsed some articles (loading via Composer or Symfony's UniversalClassLoader), followed some instructions, and still it does not work.
If someone could give me a hand with it please, I would appreciate it.
I assume you load your Silex classes in bootstrap.php like that:
// bootstrap.php
require_once __DIR__.'/vendor/autoload.php';
If so replace this code with the following:
// bootstrap.php
$loader = require __DIR__.'/vendor/autoload.php';
$loader->add(YOUR_NAMESPACE, DIRECTORY_OF_THE_NAMESPACE);
Example:
// bootstrap.php
$loader = require __DIR__.'/vendor/autoload.php';
$loader->add('Tutorial', __DIR__.'/src');
You can add multiple namespaces if you like, just call the add method for every namespace.
In src/
you would store your class files. For every namespace create a folder which contains your class files for this namespace.
The file should have the same name as the class.
MyNamespace\MyClass => src/MyNamespace/MyClass.php
MyNamespace\SubNamespace\SubClass => src/MyNamespace/SubNamespace/SubClass.php
In every class file you have to set the associated namespace in the first line.
// src/Tutorial/DemoController.php
namespace Tutorial;
class DemoController{
// class definition goes here..
}
You have now access to your classes in every file which includes bootstrap.php.
In /app/MainController.php you can now access your own class like this:
// app/MainController.php
use Tutorial\DemoController;
$foo = new DemoController();
This solution worked for me. Hope it works for you.
I was also looking for the same thing, since Silex documentation still has the registerNamespace function that was removed.
Found a really nice answer here
In Short, all you have to do, is add a "psr-0" in "autoload" section in the composer.json
Example composer.json:
{
"require": {
"silex/silex": "~1.3",
"doctrine/dbal": "~2.2"
},
"autoload": {
"psr-0": {
"MyApp": "src/"
}
}
}
Make sure to update the Composer Autoloader ("composer install" or "composer update")
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