Post on 20-Jun-2015
description
Система роутинга в symfony 1.2
Alex Demchenkopilo.uanic@gmail.comI love Symfony for 2+ years
['UA camp']
Кто я ? Люблю symfony уже 2+ года
Team lead of Lazy Ants (web2.0services.de)
['UA camp']
О чем поговорим? Что такое роутинг и как его использовать
Как настраивать роутинг правила
Дополнительные возможности роутинга
['UA camp']
Роутинг-класс это объект корневого уровня в
symfony 1.2
sfRoute
['UA camp']
Объект роутинга включает в себя всю логику:
сопоставление URL генерация URL
['UA camp']
Дополнительные параметры роута
method: PUT, POST, GET, …format: html, json, css, …host: имя хостаis_secure: https?request_uri: запрашиваемый URIprefix: Префикс добавляемый каждому с генерированному роуту
['UA camp']
Конфигурация роута по умолчаниюfrontend/config/factories.ymlrouting: class: sfPatternRouting param: load_configuration: true suffix: . default_module: default default_action: index variable_prefixes: [':'] segment_separators: ['/', '.'] variable_regex: '[\w\d_]+' debug: %SF_DEBUG% logging: %SF_LOGGING_ENABLED% cache: class: sfFileCache param: automatic_cleaning_factor: 0 cache_dir: %SF_CONFIG_CACHE_DIR%/routing lifetime: 31556926 prefix: %SF_APP_DIR%
['UA camp']
Конфигурация роута по умолчанию
variable_prefixes: [':']'/article/$year/$month/$day/$title' вместо '/article/:year/:month/:day/:title'.
segment_separators: ['/', '.']'/article/:year-:month-:day/:title'
['UA camp']
Конфигурация роута опции 1.2generate_shortest_url: генерация коротких URL, насколько это возможно
extra_parameters_as_query_string: генерация дополнительных параметров в виде запроса
['UA camp']
generate_shortest_urlarticles: url: /articles/:page param: { module: article, action: list, page: 1 } options: { generate_shortest_url: true }
echo url_for('@articles?page=1'); с генерирует /articles и /articles/1 в symfony 1.1
['UA camp']
extra_parameters_as_query_stringarticles: url: /articles options: { extra_parameters_as_query_string: true }
echo url_for('@articles?page=1'); с генерирует /articles?page=1и не будет совпадать с таким роутом в symfony 1.1
['UA camp']
Стандартные классы роутинга
sfRoutesfRequestRoutesfObjectRoutesfPropelRoute
['UA camp']
Каждый роут, определенный в routing.yml, преобразуется в объект
класса sfRoute
article: url: /article/:id param: { module: article, action: index } class: myRoute
['UA camp']
sfRequestRoute работа с методамиHTTP: GET, POST, HEAD, DELETE и PUT
post: url: /post/:id class: sfRequestRoute requirements: sf_method: get echo link_to('Great article', '@article?id=1&sf_method=get'));
['UA camp']
sf_method — нафиг нужен
/user/new + GET => user/new/user + GET => user/index
/user + POST => user/create
['UA camp']
sf_method — нафиг нужен
/user/1 + GET => user/show?id=1/user/1/edit + GET => user/edit?id=1
/user/1 + PUT => user/update?id=1
/user/1 + DELETE => user/delete?id=1
['UA camp']
sfObjectRoute — роуты как объектыpost: url: /post/:id params: { module: blog, action: show } class: sfObjectRoute options: { model: psBlog, type: object, method: getById } requirements: id: \d+В postActions: public function executeShow(sfWebRequest $request) { $this->post = $this->getRoute()->getObject(); }
['UA camp']
sfObjectRoute — роуты как объектыclass psBlog extends BasepsBlog{ static public function getById($parameters) { return psBlogPeer::retrieveByPk($parameters['id']); }}
В шаблоне:<?php echo $post->getTitle() ?>
['UA camp']
sfPropelRoute связь роута модельюblog: url: /blog params: { module: blog, action: list } class: sfPropelRoute options: { model: psBlog, type: list}
В postActions: public function executeBlog(sfWebRequest $request) { $this->blog = $this->getRoute()->getObjects(); }
['UA camp']
sfPropelRoute связь роута модельюВ шаблоне:<?php foreach ($blog as $post): ?> <?php echo $post->getTitle() ?><br /><?php endforeach; ?>
['UA camp']
sfPropelRoute — url_for() helper<?php echo url_for('blog', $blog) ?>
С дополнительными параметрами:
<?php echo url_for('blog', array('sf_subject' => $blog, 'sf_method' => 'get')) ?>
<?php echo url_for('post', array('id' => $post->getId(), 'slug' => $post->getSlug())) ?>
<?php echo url_for(@post?id='.$post->getId(). '&slug='.$post->getSlug()) ?>
['UA camp']
sfPropelRoute виртуальные поляpost_slug: url: /post/:id/:post_slug params: { module: blog, action: show } class: sfPropelRoute options: { model: psBlog, type: object } requirements: id: \d+ sf_method: [get]
['UA camp']
class psBlog extends BasepsBlog{ public function getPostSlug() { return Blog::slugify($this->getTitle()); }}
['UA camp']В шаблоне:<?php foreach ($blog as $post): ?> <?php echo link_to($post->getTitle(), 'post_slug', $post) ?><br /><?php endforeach; ?>
['UA camp']
allow_empty: truehttp://../frontend_dev.php/post/3
['UA camp']
Группа роутов
sfRouteCollectionsfObjectRouteCollectionsfPropelRouteCollection
['UA camp']
sfPropelRouteCollection
blog: class: sfPropelRouteCollection options: { model: psBlog, module: Blog}
['UA camp']
php symfony app:routes frontendlist: blog GET /blog.:sf_formatnew: blog_new GET /blog/new.:sf_formatcreate: blog_create POST /blog.:sf_formatedit: blog_edit GET /blog/:id/edit.:sf_formatupdate: blog_update PUT /blog/:id.:sf_formatdelete: blog_delete DELETE /blog/:id.:sf_format
['UA camp']
sfPropelRouteCollection — optionsmodel: имя моделиactions: список экшенов из 7 доступныхmodule: имя модуляprefix_path: префик к каждому роутуcolumn: имя поля primary key (id по умолчанию)with_show: добалять метод show или нетsegment_names: другие имена для new и edit экшеновmodel_methods: медоты для получения объектовrequirements: требования к параметрамroute_class: sfObjectRoute для sfObjectRouteCollection и sfPropelRoute для sfPropelRouteCollectionwith_wildcard_routes: позволяет добавлять новые маршруты для объектов, роуты для акшинов, которые управляют списками
['UA camp'] php symfony app:routes frontend blog_new
>> app Route "blog_new" for application "frontend"Name blog_newPattern /blog/.:sf_formatClass sfPropelRouteDefaults action: 'new' module: 'blog' sf_format: 'html'Requirements id: '\\d+' sf_method: 'get'Options context: array () debug: false extra_parameters_as_query_string: true generate_shortest_url: true load_configuration: false logging: false model: 'psBlogPeer' object_model: 'psBlog' segment_separators: array (0 => '/',1 => '.',) segment_separators_regex: '(?:/|\\.)' suffix: '' text_regex: '.+?' type: 'object' variable_content_regex: '[^/\\.]+' variable_prefix_regex: '(?:\\:)' variable_prefixes: array (0 => ':',) variable_regex: '[\\w\\d_]+'Regex #^ /blog /\.\:sf_format $#xTokens separator array (0 => '/',1 => NULL,) text array (0 => 'blog',1 => NULL,) separator array (0 => '/',1 => NULL,) text array (0 => '.:sf_format',1 => NULL,)
['UA camp']
php symfony propel:generate-module-for-route
frontend blog
['UA camp']class articlesActions extends sfActions{ public function executeIndex($request) {} public function executeShow($request) {} public function executeNew($request) {} public function executeCreate($request) {} public function executeEdit($request) {} public function executeUpdate($request) {} public function executeDelete($request) {} protected function processForm($request, $form) {}}
['UA camp']
Динамический роутингsfPatternRouting:appendRoute — добавляет новый роутprependRoute — добавляет роут в начала спискаinsertRouteBefore — добавляет роут перед заданым роутом
sfContext::getInstance()->getRouting()->prependRoute( 'post_by_id', // Имя роута '/post/:id', // Шаблон array('module' => 'blog', 'action' => 'show'), // Значения array('id' => '\d+'), // Требования к данным);
http://www.charnad.com/blog/symfony-dinamicheskij-routing/
['UA camp']
Роуты в actions$routing = sfContext::getInstance()->getRouting(); // роут для экшена blog/show$uri = $routing->getCurrentInternalUri(); => blog/show?id=21 $uri = $routing->getCurrentInternalUri(true); => @blog_by_id?id=21 $rule = $routing->getCurrentRouteName(); => blog_by_id
['UA camp']
Преобразование во внутренний URI$uri = 'blog/show?id=1'; $url = $this->getController()->genUrl($uri); => /blog/1 $url = $this->getController()->genUrl($uri, true);=> http://symfony.org.ua/blog/1
['UA camp']
Произвольные параметры в роутеfoo_route: url: /foo param: { tab: foobar }
bar_route: url: /bar param: { tab: testbar }
<?php echo link_to('tab 1', '@foo_route'), ' - ', link_to('tab 2', '@bar_route') ?><br /><?php echo $sf_params->get('tab'); ?>
['UA camp']
lazy_routes_deserializeapp/config/factories.yml
all: routing: class: sfPatternRouting param: generate_shortest_url: true extra_parameters_as_query_string: true lazy_routes_deserialize: true
['UA camp']
Проблема с trailing slash <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /
...
# remove trailing slash RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} ^(.*)/$ RewriteRule ^(.*)/$ $1 [R=301,L]
…
</IfModule>
['UA camp']
symfony route без symfony
sfRoute это отдельный компопнент symfony Platform
http://pookey.co.uk/blog/archives/79-Playing-with-symfony-routing-without-symfony.html
['UA camp']
Спасибо за внимание
['UA camp']
Alex Demchenko
pilo.uanic@gmail.com
http://web2.0services.dehttp://lazy-ants.de