Botnary / wp-slim-framework

Slim framework as Wordpress plugin
73 stars 26 forks source link

DI Container Clash #4

Closed khushroo-mistry closed 9 years ago

khushroo-mistry commented 9 years ago

I have installed the plugin on a wordpress instance as prescribed. I am using this Slim application in 2 plugins. When I create an object in the DI container in one plugin the container gets overwritten by the container created and used in the other plugin. I can make the index files of the 2 projects available on request. Wouldn't mind a simple example on how to use this slim plugin with 2 other plugins.

Could you advise?

khushroo-mistry commented 9 years ago

Resolved by naming the application context uniquely in each plugin.

Botnary commented 9 years ago

Sorry for late reply, i personally use it on my build on multiple plugins, never had a problem like this, the only problem i had was the request URI conflict.

khushroo-mistry commented 9 years ago

Sorry one more question do you use the one common application context for all your plugins? or you create a new one for each???

Do you just use Slim::getInstance() on all your plugins to get the one instance and use it?

Botnary commented 9 years ago

I use the same context in all of them, and i access it only when the route get's called.

    function __construct(){
        add_action('slim_mapping',array(&$this,'slim_mapping');            
    }

    function slim_mapping($slim){
        //$slim here is the Slim app context, i don't access it by calling Slim::getInstance()
        //if needed the class context
        $context = $this;        
        $slim->get('/slim/api/user/:u',function($user)use($context, $slim){
              $context->printUser($user);            
        });
        $slim->put('/slim/api/user/:id',function($id)use($context,$slim){
               $request = json_decode($slim->request()->getBody()); // an example of accessing slim functionality in our route.
               $context->updateUser($id);
        });
        //.... and so on
    }

In case you need to register some midlewares then we need to add more wordpress hooks like do_action('slim_before_routes',$slimInstance) before the hook do_action('slim_mapping'.$slimInstance) something like this:

add_action('init', function () {
    if (strstr($_SERVER['REQUEST_URI'], get_option('slim_base_path','slim/api/'))) {
        $slim = new \Slim\Slim();
        do_action('slim_before_routes',$slim); // by calling add_action('slim_before_routes') you have access to slim instance and do what ever you want with it, like add some midlewares.
        do_action('slim_mapping',$slim);        
        $slim->run();
        exit;
    }
});
khushroo-mistry commented 9 years ago

Thank you