How can i define global variables in slim framework

可紊 提交于 2019-12-04 11:47:17

You can inject a value into the app object:

$app->foo = 'bar';

More on Slim’s documentation.

Injection is not working in the callback function.

To have access to the variable in a callback function you can use "use() " function :

$mydata =  array (  ... );

$app->get('/api', function(Request $request, Response $response) use($mydata) {  
        echo json_encode($mydata);

});
Drinkynet

Inject the object it like this:

$app->companies = new Companies();

You can also inject it as a singleton if you want to make sure its the same one each time:

$app->container->singleton('companies', function (){
    return new Companies();
});

The call it like this:

$app->companies->find($_SESSION['company_id']);

UPDATE DOC LINK: Slim Dependency Injection

The accepted answer does not work for Slim 3 (as the hooks have been removed).

If you are trying to define a variable for all views and you are using the PhpRenderer, you can follow their example:

// via the constructor
$templateVariables = [
    "title" => "Title"
];
$phpView = new PhpRenderer("./path/to/templates", $templateVariables);

// or setter
$phpView->setAttributes($templateVariables);

// or individually
$phpView->addAttribute($key, $value);

i was finally able to get it to work with this

   $app->hook('slim.before.dispatch', function() use ($app) { 
       $current_company = null;
       if (isset($_SESSION['company_id'])) {
          $current_company = Company::find($_SESSION['company_id']);
       }
       $app->view()->setData('current_company', $current_company);
    });
tiron

With twig/view

creating a middleware

<?php

namespace ETA\Middleware;

class GlobalVariableMiddleware extends Middleware {

    public function __invoke($request, $response, $next) {

        $current_path = $request->getUri()->getPath();

        $this->container->view->getEnvironment()->addGlobal('current_path', $current_path);

        return $next($request, $response);
    }

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!