duanqiongdu9916 2016-07-28 09: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 09: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部