How can i define global variables in slim framework

隐身守侯 提交于 2020-01-23 01:11:30

问题


How can i define a global variable such that my current_user method can work were ever i want it to, all i simple need to do is check if there is a current user my example code is below

    if (isset($_SESSION['company_id'])) {
       $current_user = Companies::find($_SESSION['company_id']);
     }
    else
   {
    $current_company = null;
   }

how can i use the current user method where ever i want without passing it to my app->render() method just like in my header.html

{% if current_user %}
 hi {{current_user.name}}
{% endif %}

回答1:


You can inject a value into the app object:

$app->foo = 'bar';

More on Slim’s documentation.




回答2:


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);

});



回答3:


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




回答4:


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);



回答5:


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);
    });



回答6:


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);
    }

}


来源:https://stackoverflow.com/questions/23645185/how-can-i-define-global-variables-in-slim-framework

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