Search code examples
phpsymfonybundlevendor

Symfony bundle allow custom provider


I'm developing a bundle for the community.

My bundle has a service to get some content. I have a folder called Providers with some providers and an AbstractProvider class. All my providers extends the AbstractProvider.

When the developer calls my service's function with a string such as "my_class", I instantiate the class from my providers using this name:

<?php
new MyClass();

In the Providers folder, I have some common providers but I want to allow the developer to add its own providers (extending my AbstractProvider class). My service must instantiate this custom provider using the class name.

How can I achieve this goal?

Here is my tree:

MyBundle
└── Toto
    └── Providers
        ├── AbstractProvider.php
        ├── ArticleProvider.php
        ├── BlockRubricProvider.php
        ├── CommuniqueProvider.php
        ├── HomepageProvider.php
        ├── OffreurSolutionsProvider.php
        ├── PartenaireProvider.php
        ├── PresseProvider.php
        └── PublicationProvider.php

And my service:

class MyServiceProvider
{

    public function __construct() { }

    /* $providerName exemple: "my_provider" */
    public function getProvider( $provierName )
    {
        $providerClass = str_replace('_', '', ucwords($contentType->identifier, '_'))."Provider";

        /** @var AbstractProvider $provider */
        $provider = new $providerClass( $provierName );

        return $provider;
    }
}

How to allow developers to have their own folder Providers with their providers and allow my service to instantiate it with this system ?

Maybe something like this ?

use **\Toto\Providers\*;

Thanks!


Solution

  • Why you don't use the full callified name? In this case you don't need include any use. You can configure the providers with the configuration bundle like here and in your AbstractProvider you can put a abstract method to put a name for the provider that the user use to call it.

    I hope can help you