Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 989
lilly Avatar asked Dec 02 '22 23:12

lilly


2 Answers

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.

like image 158
Fatal705 Avatar answered Dec 22 '22 05:12

Fatal705


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")

like image 35
spectrumcat Avatar answered Dec 22 '22 06:12

spectrumcat