如何在php中建立自动路由器?

时间:2018-09-21 07:03:54

标签: php

我有此代码:

index.php

$router = new Core\Libraries\Router();
$router->add('', ['controller' => 'HomeAdminController', 'action' => 'index']);
$router->add('home', ['controller' => 'HomeAdminController', 'action' => 'indexAction']);
$router->add('home2', ['controller' => 'HomeAdminController', 'action' => 'indexAction2']);
$router->add('home3', ['controller' => 'HomeAdminController', 'action' => 'indexAction3']);

router.php

class Router
{
    protected $_routes = [];
    protected $_params = [];

    public function add(string $route, array $params = [])
    {
        $route = preg_replace('/\//', '\\/', $route);
        $route = preg_replace('/\{([a-z]+)\}/', '(?P<\1>[a-z-]+)', $route);
        $route = preg_replace('/\{([a-z]+):([^\}]+)\}/', '(?P<\1>\2)', $route);
        $route = '/^' . $route . '$/i';
        $this->_routes[$route] = $params;
    }


    public function getRoutes(): string
    {
        return $this->_routes;
    }


    public function match(string $url): bool
    {
        foreach ($this->_routes as $route => $params) {
            if (preg_match($route, $url, $matches)) {
                foreach ($matches as $key => $match) {
                    if (is_string($key)) {
                        $params[$key] = $match;
                    }
                }

                $this->_params = $params;
                return true;
            }
        }

        return false;
    }


    public function getParams(): string
    {
        return $this->_params;
    }


    public function dispatch(string $url)
    {
        $url = $this->removeQueryStringVariables($url);

        if ($this->match($url)) {
            $controller = $this->_params['controller'];
            $controller = $this->convertToStudlyCaps($controller);
            $controller = $this->getNamespace() . $controller;


            if (class_exists($controller)) {
                $controller_object = new $controller($this->_params);

                $action = $this->_params['action'];
                $action = $this->convertToCamelCase($action);

                if (is_callable([$controller_object, $action])) {
                    $controller_object->$action();

                } else {
                    throw new \Exception("Method $action (in controller $controller) not found");
                }
            } else {
                throw new \Exception("Controller class $controller not found");
            }
        } else {
            throw new \Exception('No route matched.', 404);
        }
    }


    protected function convertToStudlyCaps(string $string): string
    {
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
    }


    protected function convertToCamelCase(string $string): string
    {
        return lcfirst($this->convertToStudlyCaps($string));
    }

    protected function removeQueryStringVariables(string $url): string
    {
        if ($url != '') {
            $parts = explode('&', $url, 2);

            if (strpos($parts[0], '=') === false) {
                $url = $parts[0];
            } else {
                $url = '';
            }
        }

        return $url;
    }

    protected function getNamespace(): string
    {
        $namespace = null;
        $namespace = 'Controllers\\';

        if (array_key_exists('namespace', $this->_params)) {
            $namespace .= $this->_params['namespace'] . '\\';
        }
        return $namespace;
    }
}

**controllers: Home.php**
class HomeAdminController extends Controllers\Controller
{

    protected function before()
    {
    }

    protected function after()
    {
    }

    public function indexAction()
    {
        echo "@@ 1";
    }
    public function index()
    {
        echo "@@ 2";
        $config = Registry::register("Core\Libraries\Config");
        View::renderTemplate('Home/index.twig', [
            'name'    => 'Dave',
            'colours' => ['red', 'green', 'blue']
        ]);
    }

    public function indexAction2()
    {
        echo "@@ 2";
        $config = Registry::register("Core\Libraries\Config");
        View::renderTemplate('Home/home2.twig', [
            'name'    => 'Dave',
            'products' => [
                [
                    'name'          => 'Notebook',
                    'description'   => 'Core i7',
                    'value'         =>  800.00,
                    'date_register' => '2017-06-22',
                ],
                [
                    'name'          => 'Mouse',
                    'description'   => 'Razer',
                    'value'         =>  125.00,
                    'date_register' => '2017-10-25',
                ],
                [
                    'name'          => 'Keyboard',
                    'description'   => 'Mechanical Keyboard',
                    'value'         =>  250.00,
                    'date_register' => '2017-06-23',
                ],
            ]
        ]);
    }
    public function indexAction3()
    {
        echo "home 3";
        print_r($_POST);
        View::renderTemplate('Home/home2.twig', [
            'name'    => 'Dave',
            'colours' => ['red', 'green', 'blue']
        ]);
    }
}

控制者路径:Controllers \ Name.php

是否可以自动构建此类路由器? 我的意思是搜索目录:Controllers \并基于文件构建示例:

- Controllers \ home.php
- Controllers \ product.php
- Controllers \ contact.php
- Controllers \ productList.php
....

以自动方式:

$ router-> add ('', ['controller' => 'HomeAdminController', 'action' => 'index']);
$ router-> add ('home', ['controller' => 'HomeAdminController', 'action' => 'indexAction']);
  $ router-> add ('home2', ['controller' => 'HomeAdminController', 'action' => 'indexAction2']);
  $ router-> add ('home3', ['controller' => 'HomeAdminController', 'action' => 'indexAction3']);
$ router-> add (product '', ['controller' => 'Product AdminController', 'action' => 'index']);
$ router-> add ('contact', ['controller' => 'ContactAdminController', 'action' => 'index']);
$ router-> add ('productList', ['controller' => 'ProductListAdminController', 'action' => 'index']);

我想自动构建此路由器,以便不必手动进行操作。 有人知道怎么做吗?

0 个答案:

没有答案