How to use a custom class using silex ServiceProvider

I feel that I searched the entire Internet through and through, but it may not seem that this is visible. I am using Silex (latest version) and cannot figure out how to use Silex ServiceProvider to return an instance of the class to use.

I know how to create a basic service provider.

What I do not know how to do is how to get this service provider to use its own class. I tried everything that I could think of or find on the Internet. Part of the problem is that the Silex documentation on this question is not very extensive, and most of the questions asked about this type of problem were asked / answered before quite large changes were made to how it was done (or so it seems) the answers are not current.

So put it briefly: I want to use a system like Silex $ app ['myclass'] to access my class so that I can do something like $ app ['myclass'] → myMethod ().

Where I hung up is that although I can create a service provider, I cannot figure out how to get the service provider to recognize the class. I tried the whole namespace theme with pso-0 composer autoload setting and tried using things like MyClass / MyClass.

Haha, mainly because there is so little documentation, maybe some part of it that I'm doing wrong.

Does anyone write a current step-by-step process for connecting a custom library / class to the $ app variable? I think this will help not only me, but also others. Thanks!

+4
source share
1 answer

It seems to me that you have problems loading classes. This is what was previously performed by the autoload service in silex. However, this service was deleted in favor of the composer's startup.

You were on the right track by specifying autoload in composer.json . If you are new to the composer, read the introduction . For more information about how autoload works, see the autoload section of the main use chapter .

I will give you a short version here. Make sure your file names 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 base directory for your classes. For example, the Acme\Foo\Bar class will be located in src/Acme/Foo/Bar.php .

Then run php composer.phar update to reload the startup files and you can access your classes.

+7
source

Source: https://habr.com/ru/post/1444855/


All Articles