dongmo3413 2015-01-15 09:10
浏览 23

Slim框架合并数组以查看数据

I have a Slim application, in the main Middleware I add some generic data to the model

middleware "call" method code

$app->view->set("auths",["user","poweruser"]);

In a controller method I want to push a value to the "auths" array of the view model, is there any way to access it in a faster way than this?:

controller method code

$data=$app->view->get("auths");
$data[]="newauth";
$app->view->set("auths",$data);
  • 写回答

1条回答 默认 最新

  • doushun1904 2015-01-15 23:48
    关注

    In short

    No, you can't, but you could define your own view subclass if you want to wrap this functionality nicely.

    Native Slim

    I just checked out Slim's source code (which is really, really, .. Slim), and you are using its View object which wraps a Set object. Neither supplies this functionality, since the internal array isn't exposed and the all() and getData() methods don't return the internal array by reference, so this won't work:

    $view->all()['auths'][] = 'newauth';
    

    You can reach what you want directly with the following nasty one-liner:

    $view->set('auths', array_merge($view->get('auths'), ['newauth']));
    

    Roll your own View subclass

    Much better would be to define your own custom view that makes this possible!

    1. Define a custom view class

      class CustomView extends \Slim\View
      {
          public function pushProperty($key, $value)
          {
              $array = $this->get($key);
              $array[] = $value;
              $this->set($key, $array);
          }
      }
      

      Note: this method blindly assumes that the current value is an array. You will want to add some checks!

    2. Assign it as the default view object in your Slim app when you create it.

      $app = new Slim\Slim(array('view' => new CustomView()));
      
    3. And start using it :)

      $app->view->set("auths",["user","poweruser"]);
      $app->view->pushProperty('auths','newauth'); // this will now work. Yay :)
      
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog