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 如何能达到用ping0.cc检测成这样?如图
  • ¥15 关于#DMA固件#的问题,请各位专家解答!
  • ¥15 matlab生成的x1图不趋于稳定,之后的图像是稳定的水平线
  • ¥15 请问华为OD岗位的内部职业发展通道都有哪些,以及各个级别晋升的要求
  • ¥20 微信小程序 canvas 问题
  • ¥15 系统 24h2 专业工作站版,浏览文件夹的图库,视频,图片之类的怎样删除?
  • ¥15 怎么把512还原为520格式
  • ¥15 MATLAB的动态模态分解出现错误,以CFX非定常模拟结果为快照
  • ¥15 求高通平台Softsim调试经验
  • ¥15 canal如何实现将mysql多张表(月表)采集入库到目标表中(一张表)?