hoben/simple-routes

为PHP设计的简单路由包。

dev-master 2018-04-19 15:22 UTC

This package is not auto-updated.

Last update: 2024-09-29 05:41:55 UTC


README

Author Software License

简单易用的路由器,专为初学者和轻量级项目构建。

此包符合[PSR-2]

安装

通过Composer

$ composer require hoben/simple-routes

要求

  • PHP ^5.5.9 | >=7.0.8
  • Symfony/yaml: ^3.4

特性

  • 创建由yaml文件定义的路由
  • 您也可以使用Router.php类中的add函数在代码中添加路由
  • 您可以根据方法(GET、POST、PUT、DELETE等)过滤路由

通过yaml文件(routes.yaml)添加路由

"Dashboard":
  url: /
  controller: indexController
  action: index
  method: GET

"Test Page":
  url: /
  controller: indexController
  action: showTest
  method: POST

"default":
  controller: defaultController
  action: show404
$router = new Router();
$router->setBasePath('my-app/'); // Example: for www.localhost/my-app
$router->setControllersPath('src/controllers/'); // Example: for controllers in www.localhost/my-app/src/controllers
$router->setConfigPath('yaml-file-path/routes.yaml') // The yaml file path
$router->match();

通过PHP代码添加路由

use Hoben\SimpleRoutes\Router;

$router = new Router();

$route->add('/products', 'ProductController', 'getProducts', 'GET');
$route->add('/product', 'ProductController', 'getProduct', 'GET');
$route->add('/product', 'ProductController', 'addProduct', 'POST');
$route->add('/product', 'ProductController', 'updateProduct', 'PUT');

$router->setBasePath('my-app/'); // Example: for www.localhost/my-app
$router->setControllersPath('src/controllers/'); // Example: for controllers in www.localhost/my-app/src/controllers
$router->match();

bonus:如何将所有URL重定向到index.php

如果您使用Apache且mod_rewrite已启用,请在根目录创建一个简单的.htaccess文件。

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)$ index.php [NC,L]

如果您使用nginx,请按照以下方式设置服务器部分

server {
	listen 80;
	server_name mywebsite.dev;
	root /var/www/mywebsite/public;

	index index.php;

	location / {
		try_files $uri $uri/ /index.php?$query_string;
	}

	location ~ \.php$ {
		fastcgi_split_path_info ^(.+\.php)(/.+)$;
		# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

		# With php5-fpm:
		fastcgi_pass unix:/var/run/php5-fpm.sock;
		fastcgi_index index.php;
		include fastcgi.conf;
		fastcgi_intercept_errors on;
	}
}

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件