Reputation: 7599
I feel like I have searched the entire internet through and through, but cannot seem to figure this one out. I'm using Silex (the latest version) and cannot seem to figure out how to use Silex's ServiceProvider system to return an instance of a class for use.
I do know how to create a basic service provider.
What I do not know how to do is how to have this service provider use a custom class. I've tried everything I can think of or find on the web. Part of the problem is that Silex's documentation on this is not very extensive, and most of the questions that have been ask about this type of issue were asked/answered before a pretty large change to how it was done (or so it seems) so the answers are not current.
So, put briefly: I want to use Silex's $app['myclass'] type system to access my class, so that I can do things like $app['myclass']->myMethod().
Where I'm hung up is this, while I can create a service provider, I can't figure out how to get the service provider to recognize the class. I've tried the whole namespace thing with the composer auto-load pso-0 set up, and have tried use MyClass/MyClass type things.
Haha, basically, because there is so little documentation, there could be any part of it that I am doing wrong.
Would someone write a current step-by-step process for hooking up a custom library/class to the $app variable? I think this would help not only me, but also others. Thanks!
Upvotes: 4
Views: 1672
Reputation: 28269
Seems to me like you are having issues with class loading. This is something that used to be handled by the autoload
service in silex. That service was removed however, in favour of composer's autoloading.
You were on the right track with specifying the autoloading in composer.json
. In case you're not familiar with composer, read the introduction. For details on how the autoloading works, see the autoloading section of the basic usage chapter.
I will give you the short version here. Make sure your filenames comply with the PSR-0 naming standard. Add this to your composer.json
:
{
"autoload": {
"psr-0": {"Acme": "src/"}
}
}
You need to replace Acme
with your namespace and src
with the base directory for your classes. For example, the class Acme\Foo\Bar
would be located in src/Acme/Foo/Bar.php
.
Then run php composer.phar update
to get the autoload files re-dumped and you should be able to access your classes.
Upvotes: 7