【问题标题】:Phalconphp: Getting router parameters outside of ControllerPhalconphp:在控制器之外获取路由器参数
【发布时间】:2015-03-31 15:52:46
【问题描述】:

我有一个这样定义的路由器

$router->add("/api/:controller/:action/:params", array(
    'controller' => 1,
    'action' => 2,
    'params' => 3,
    'myParameter' => 'test'
));

所以,我可以像这样在控制器内部获取“myParameter”参数

$this->dispatcher->getParam("myParameter");

但是,我想在我从 Controller 调用的另一个类中使用这个参数。像

myCustomClass::test();


class myCustomClass {
    function test() {
        // this is where I need that parameter
    }
}

如果我从 myCustomClass 调用 Dispatcher,则不会返回任何内容。

(当然,获取控制器内部的值并将其作为值传递是一种解决方案,但我可能至少会在 100 种不同的操作中使用它,因此在这种情况下它并不是一个真正好的解决方案)。

有没有办法让那个额外的参数超出控制器的范围。

【问题讨论】:

    标签: php phalcon phalcon-routing


    【解决方案1】:

    您需要默认依赖注入,可能在 index.php 中声明。

    class myCustomClass {
        static function test() {
            $request = \Phalcon\DI::getDefault()->get( 'request' );
            $request->get("myParameter");
        }
    }
    

    此外,您还缺少函数中的 STATIC 字。

    【讨论】:

    • (对不起,我的代码中已经有静态,忘记在这里粘贴了),但是这个仍然没有给我任何结果。与 shivanshupatel 的回答相同。
    • 看起来不错,但我有一种奇怪的感觉:不应该是来自dispatcher而不是request吗?
    • @yergo dispatcher 控制应用程序流,控制器排序。请求访问来自 URL、GET、POST 等的信息。
    【解决方案2】:

    我不是 100% 确定,但我认为您可以从 phalcon Http 请求类访问获取参数。

    $request = new Phalcon\Http\Request();
    $request->get("myParameter");
    

    【讨论】:

    • 试过了,它返回实际的请求参数(获取和发布)。对于这个 url,'/api/user/profile/1?x=y&a=b' $request->get() 是 Array ( [_url] => /api/user/profile/1 [x] => y [ a] => b)
    猜你喜欢
    • 2016-10-21
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 2013-03-04
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多