源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

ThinkPHP、ZF2、Yaf、Laravel框架路由大比拼

  • 时间:2021-01-13 03:32 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:ThinkPHP、ZF2、Yaf、Laravel框架路由大比拼
前言 读过一篇关于Zend Framework2的技术文章《ZF2多级树形路由Route配置实例》,是介绍路由配置的。我觉得很有意思,这是的需求: /user对应用户列表页面 /user/:user_id对应用户的个人主页,比如 /user/AlloVince 就对应AlloVince用户的个人主页 /user/:user_id/blog/对应用户的博客列表页面,比如 /user/AlloVince/blog 就会列出AlloVince写过的Blog /user/:user_id/blog/:blog_id对应用户的一篇博客文章 方案引用自原文:
'router' => array(
  'routes' => array(
    'user' => array(
      'type' => 'Segment',
      'options' => array(
        'route' => '/user[/]',
        'defaults' => array(
          'controller' => 'UserController',
          'action' => 'index',
        ),
      ),
      'may_terminate' => true,
      'child_routes' => array(
        'profile' => array(
          'type' => 'Segment',
          'options' => array(
            'route' => '[:id][/]',
            'constraints' => array(
              'id' => '[a-zA-Z0-9_-]+'
            ),
            'defaults' => array(
              'action' => 'get'
            ),
          ),
          'may_terminate' => true,
          'child_routes' => array(
            'blog' => array(
              'type' => 'Segment',
              'options' => array(
                'route' => 'blog[/]',
                'constraints' => array(
                ),
                'defaults' => array(
                  'action' => 'blog'
                )
              ),
              'may_terminate' => true,
              'child_routes' => array(
                'post' => array(
                  'type' => 'Segment',
                  'options' => array(
                    'route' => '[:post_id][/]',
                    'constraints' => array(
                      'post_id' => '[a-zA-Z0-9_-]+'
                    ),
                    'defaults' => array(
                      'action' => 'post'
                    )
                  ),
                  'may_terminate' => true,
                ),
              ),
            ),
          ), //profile child_routes end
        ), //profile end
      ), //user child_routes end
    ), //user end
  ),
),
看了这篇文章后,我打算使用我用过的PHP框架来实现这个路由需求。 [b]ThinkPHP[/b] 新建一个ThinkPHP项目:
[url=http://127.0.0.1/tp/url]http://127.0.0.1/tp/url[/url] 输出:
[url=/tp/user] <a href="/tp/user/jing">/tp/user/jing<a/><br /> <a href="/tp/user/jing/blog">/tp/user/jing/blog<a/><br /> <a href="/tp/user/jing/blog/1">/tp/user/jing/blog/1<a/><br />
访问上面4个链接,依次返回: 我是用户列表^_^ 欢迎你,jing 这是jing的博客列表 jing的这篇博客的id为1 下面其他框架,也同样输出以上内容。 [b]Zend Framework 2[/b] 使用ZF2骨架程序创建一个ZF2项目: composer create-project --stability="dev" zendframework/skeleton-application zf2 修改默认模块Application的配置文件zf2\module\Application\config\module.config.php:
<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link   http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license  http://framework.zend.com/license/new-bsd New BSD License
 */
return array(
  'router' => array(
    'routes' => array(
      'home' => array(
        'type' => 'Zend\Mvc\Router\Http\Literal',
        'options' => array(
          'route' => '/url',
          'defaults' => array(
            'controller' => 'Application\Controller\User',
            'action' => 'url',
          ),
        ),
      ),
      // The following is a route to simplify getting started creating
      // new controllers and actions without needing to create a new
      // module. Simply drop new controllers in, and you can access them
      // using the path /application/:controller/:action
      'application' => array(
        'type' => 'Literal',
        'options' => array(
          'route' => '/application',
          'defaults' => array(
            '__NAMESPACE__' => 'Application\Controller',
            'controller' => 'Index',
            'action' => 'index',
          ),
        ),
        'may_terminate' => true,
        'child_routes' => array(
          'default' => array(
            'type' => 'Segment',
            'options' => array(
              'route' => '/[:controller[/:action]]',
              'constraints' => array(
                'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
              ),
              'defaults' => array(
              ),
            ),
          ),
        ),
      ),
      'user_list' => array(
        'type' => 'Segment',
        'options' => array(
          'route' => '/user[/]',
          'defaults' => array(
            '__NAMESPACE__' => 'Application\Controller',
            'controller' => 'User',
            'action' => 'index',
          ),
        ),
        'may_terminate' => true,
        'child_routes' => array(
          'user' => array(
            'type' => 'Segment',
            'options' => array(
              'route' => '[:name][/]',
              'constraints' => array(
                'name' => '[a-zA-Z0-9_-]+',
              ),
              'defaults' => array(
                'action' => 'show',
              ),
            ),
            'may_terminate' => true,
            'child_routes' => array(
              'blog_list' => array(
                'type' => 'Segment',
                'options' => array(
                  'route' => 'blog[/]',
                  'constraints' => array(
                  ),
                  'defaults' => array(
                    'controller' => 'Blog',
                    'action' => 'index',
                  )
                ),
                'may_terminate' => true,
                'child_routes' => array(
                  'blog' => array(
                    'type' => 'Segment',
                    'options' => array(
                      'route' => '[:blog_id]',
                      'constraints' => array(
                        'blog_id' => '[0-9]+',
                      ),
                      'defaults' => array(
                        'action' => 'show',
                      )
                    ),
                    'may_terminate' => true,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    ),
  ),
  'service_manager' => array(
    'abstract_factories' => array(
      'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
      'Zend\Log\LoggerAbstractServiceFactory',
    ),
    'aliases' => array(
      'translator' => 'MvcTranslator',
    ),
  ),
  'translator' => array(
    'locale' => 'en_US',
    'translation_file_patterns' => array(
      array(
        'type' => 'gettext',
        'base_dir' => __DIR__ . '/../language',
        'pattern' => '%s.mo',
      ),
    ),
  ),
  'controllers' => array(
    'invokables' => array(
      'Application\Controller\Index' => 'Application\Controller\IndexController',
      'Application\Controller\User' => 'Application\Controller\UserController',
      'Application\Controller\Blog' => 'Application\Controller\BlogController',
    ),
  ),
  'view_manager' => array(
    'display_not_found_reason' => true,
    'display_exceptions' => true,
    'doctype' => 'HTML5',
    'not_found_template' => 'error/404',
    'exception_template' => 'error/index',
    'template_map' => array(
      'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
      'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
      'error/404' => __DIR__ . '/../view/error/404.phtml',
      'error/index' => __DIR__ . '/../view/error/index.phtml',
    ),
    'template_path_stack' => array(
      __DIR__ . '/../view',
    ),
  ),
  // Placeholder for console routes
  'console' => array(
    'router' => array(
      'routes' => array(
      ),
    ),
  ),
);
?>

这个文件是骨架程序中自带的,我只是修改了router部分和controllers部分。要我写这么长的文件,那就太为难我了。这也是ZF官方发布了一个骨架程序的原因。 创建文件zf2\module\Application\src\Application\Controller\UserController.php:
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class UserController extends AbstractActionController {
  public function urlAction() {
    $name = 'jing';
    $blogId = 1;
    $urls = array(
      $this->url()->fromRoute('user_list'),
      $this->url()->fromRoute('user_list/user', array('name' => $name)),
      $this->url()->fromRoute('user_list/user/blog_list', array('name' => $name)),
      $this->url()->fromRoute('user_list/user/blog_list/blog', array('name' => $name, 'blog_id' => $blogId)),
    );
    $view = new ViewModel(compact('urls'));
    $view->setTerminal(true);
    return $view;
  }
  public function indexAction() {
    $view = new ViewModel();
    // 禁用布局模板
    $view->setTerminal(true);
    return $view;
  }
  public function showAction() {
    $username = $this->params()->fromRoute('name');
    $view = new ViewModel(compact('username'));
    $view->setTerminal(true);
    return $view;
  }
}
?>

创建文件zf2\module\Application\src\Application\Controller\BlogController.php:
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class BlogController extends AbstractActionController {
  public function indexAction() {
    $username = $this->params()->fromRoute('name');
    $view = new ViewModel(compact('username'));
    $view->setTerminal(true);
    return $view;
  }
  public function showAction() {
    $username = $this->params()->fromRoute('name');
    $blogId = $this->params()->fromRoute('blog_id');
    $view = new ViewModel(compact('username', 'blogId'));
    $view->setTerminal(true);
    return $view;
  }
}
?>

zf2不支持Action参数绑定,ThinkPHP不仅支持绑定,还支持2种绑定方式:按变量名绑定和按变量顺序绑定。 zf2中Action必须得返回视图,除非exit()。如果你知道可以禁用视图的办法,请告诉我。 创建文件zf2\module\Application\view\application\user\url.phtml:
<?php foreach ($urls as $url): ?>
<a href="<?php echo $url;?>"><?php echo $url;?><a/><br />
<?php endforeach; ?>
创建文件zf2\module\Application\view\application\user\index.phtml: 我是用户列表^_^ 创建文件zf2\module\Application\view\application\user\show.phtml: 欢迎你,<?php echo $username; ?> 创建文件zf2\module\Application\view\application\blog\index.phtml: 这是<?php echo $username; ?>的博客列表 创建文件zf2\module\Application\view\application\blog\show.phtml: [b]Yaf[/b] 安装Yaf 使用代码生成工具创建Yaf项目 修改启动文件yaf\application\Bootstrap.php,修改其中的_initRoute方法:
    $router = Yaf_Dispatcher::getInstance()->getRouter();
    $route0 = new Yaf_Route_Rewrite('url', array(
      'controller' => 'User',
      'action' => 'url',
        ), array()
    );
    $route1 = new Yaf_Route_Rewrite('user', array(
      'controller' => 'User',
      'action' => 'index',
        ), array()
    );
    $route2 = new Yaf_Route_Regex('#user/([a-zA-Z0-9_-]+)#', array(
      'controller' => 'User',
      'action' => 'show',
        ), array(1 => 'name',)
    );
    $route3 = new Yaf_Route_Regex('#user/([a-zA-Z0-9_-]+)/blog#', array(
      'controller' => 'Blog',
      'action' => 'index',
        ), array(1 => 'name',)
    );
    $route4 = new Yaf_Route_Regex('#user/([a-zA-Z0-9_-]+)/blog/([0-9]+)#', array(
      'controller' => 'Blog',
      'action' => 'show',
        ), array(1 => 'name', 2 => 'blogId',)
    );
    $router->addRoute('url', $route0);
    $router->addRoute('user_list', $route1);
    $router->addRoute('user', $route2);
    $router->addRoute("blog_list", $route3);
    $router->addRoute("blog", $route4);

Yaf有路由功能,但是没有根据路由名生成URL的方法。所以我定义了一个项目名,用于拼接URL。 在配置文件中添加配置项yaf\conf\application.ini:
[url=]'UserController@getUrl'[/url])); Route::get('/user', array('uses' => [url=]'UserController@getIndex'[/url])); Route::get('/user/{username}', array('uses' => [url=]'UserController@getShow'[/url])); Route::get('/user/{username}/blog', array(     'as' => 'blog_list',     'uses' => [url=]'BlogController@getIndex'[/url], )); Route::get('/user/{username}/blog/{blogId}', array(     'as' => 'blog',     'uses' => [url=]'BlogController@getShow'[/url], ))->where(array('blogId' => '[0-9]+'));
查看路由定义情况:
[url=]'UserController@getShow'[/url], array($name)),             route('blog_list', array($name)),             route('blog', array($name, $blogId)),         );         foreach ($urls as $url) {             echo "<a href=\"{$url}\">{$url}<a/><br />\n";         }     }     public function getIndex() {         echo '我是用户列表^_^';     }     public function getShow($name) {         echo "欢迎你,{$name}";     } }
创建BlogController控制器:
[u]复制代码[/u] 代码如下:
php artisan make:controller BlogController
修改文件laravel\app\Http\Controllers\BlogController.php:
[u]复制代码[/u] 代码如下:
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; class BlogController extends Controller {     public function getIndex($name) {         echo "这是{$name}的博客列表";     }     public function getShow($name, $blogId) {         echo "{$name}的这篇博客的id为{$blogId}";     } }
Laravel的Action也支持参数绑定,是按变量顺序绑定的,和变量名无关。 [b]后语[/b] 我是Laravel粉,但是我也没有想黑其他框架的意思,大家有兴趣也可以用自己熟悉的框架来实现这个小例子,写了记得@我,语言不限。 以上所述就是本文的全部内容了,希望大家能够喜欢。 请您花一点时间将文章分享给您的朋友或者留下评论。我们将会由衷感谢您的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部