【问题标题】:PHP AltoRouter Pass a route completely to a controllerPHP AltoRouter 将路由完全传递给控制器
【发布时间】:2016-03-24 21:28:03
【问题描述】:

使用 AltoRouter,我需要将任何以 /customer 开头的请求传递给某个 path/to/CustomerController.php 文件,然后在那里进行我所有的特定匹配。

CustomerController.php 我会匹配我所有的方法,即:

public static function Transfer(){... this will be invoked from /customer/transfer...
public static function Register(){... this will be invoked from /customer/register...

在 Laravel 中,您可以这样做:

Route::controller("customer", 'CustomerController');

我需要完全相同的东西,但使用 AltoRouter。我找不到任何方法来做到这一点

http://altorouter.com/

(我只是不想让一个路由文件处理我网站上的所有控制器方法,而是让每个控制器处理所有特定路由的方法)

【问题讨论】:

    标签: php altorouter


    【解决方案1】:

    我在文档中找到了以下代码 sn-p 可能对你有帮助:

    // map users details page using controller#action string
    $router->map( 'GET', '/users/[i:id]/', 'UserController#showDetails' );
    

    如果这没有帮助,您可以查看我的路由器 Sail。我构建它是为了让程序员以更加面向对象的方式来构建他们的 API。

    编辑

    这是一个如何使用 Sail 解决此问题的示例。

    use Sail\Sail;
    use Sail\Tree;
    use Sail\Exceptions\NoSuchRouteException;
    use Sail\Exceptions\NoMiddlewareException;
    use Sail\Exceptions\NoCallableException;
    
    require '../vendor/autoload.php';
    
    $sail = new Sail();
    
    class UserController extends Tree {
    
        public function build () {
            $this->get('transfer', function($request, $response) {
                self::transfer($request, $response);
            });
    
            $this->get('register', function($request, $response) {
                self::register($request, $response);
            });
        }
    
        public static function transfer(&$request, &$response) {
            //do your stuff
        }
    
        public static function register(&$request, &$response) {
            //do your stuff
        }
    }
    
    $sail->tree('customer', new UserController());
    
    try {
        $sail->run();
    } catch (NoSuchRouteException $e) {
        echo $e->getMessage();
    } catch (NoMiddlewareException $e) {
        echo $e->getMessage();
    } catch (NoCallableException $e) {
        echo $e->getMessage();
    }
    

    【讨论】:

    • 不,这不起作用...并且您正在该路线图示例中的 UserController(showdetails) 下收集特定方法...。请记住,我想要一张地图发送所有流量以/users 到控制器。 PS:您也没有提供使用 Sail 路由器的示例。
    • @GabrielRodriguez 我在帖子中添加了一个示例!解决问题的另一种方法是编写自己的映射函数,该函数从 UserController 读取所有方法并以这种方式添加它们: $router->map( 'GET', '/consumer/functionName', 'UserController#functionName' ) ;
    • @GabrielRodriguez 看看这个方法php.net/manual/de/function.get-class-methods.php
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 2017-01-12
    • 2016-04-16
    相关资源
    最近更新 更多