lilly lilly - 5 months ago 89
PHP Question

Silex, loading own classes

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.

Answer

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.