duanqiongdu9916 2016-07-28 17:14
浏览 17
已采纳

如何创建一个操作实例的辅助函数?

I am busy learning as much as I can about php frameworks.

At the moment I have a file full of routes. The routes take this general form.

$bootstrap->router->add('/home', ['controller' => 'home', 'action' => 'index']);

So, the 'routes' file is not a class, it is just a file which I include into the index.php page just underneath $bootstrap = new Bootstrap($router);.

As you can see, to add a route I add it to the instantiated $bootstrap object, which itself has an instantiated ->router object inside which I am calling the 'add()' method.

Now I want to make it easier to add routes by writing something like this...

route('/home', ['controller' => 'home', 'action' => 'index']);

question

Exactly how to go about this is unclear... I am not even sure if this is a done thing. I have tried making a 'helpers/RoutesHelper file' but that takes my request out of the object scope...

...so I am a bit confused, how do I go about implementing a plane old helper function inside object oriented code?

Many thanks in advance.

  • 写回答

2条回答 默认 最新

  • douxian0008 2016-07-28 17:27
    关注

    anonymous function

    If you are willing to add a $ to the beginning of that route(... line:

    $route = function($path, $options) use ($bootstrap) {
         $bootstrap->router->add($path, $options);
    }
    

    would work.

    global $bootstrap

    Otherwise it would be dirty to bring the bootstrap object into the route function:

    function route($path, $options) {
         global $bootstrap; // <-- i don't like this
         $bootstrap->router->add($path, $options);
    }
    

    definitions in array

    you could also just make an array in your file like:

    $routes = array()
    $routes['/home'] = ['controller' => 'home', 'action' => 'index'];
    // ... more routes ...
    

    and in your main program just loop over that array:

    foreach($routes as $path => $options) {
        $bootstrap->router->add($path, $options);
    }
    

    those are the three solutions that pop into my mind ...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。