routing system in symfony 1.2

41
Система роутинга в symfony 1.2 Alex Demchenko [email protected] I love Symfony for 2+ years

Upload: alex-demchenko

Post on 20-Jun-2015

3.702 views

Category:

Self Improvement


1 download

DESCRIPTION

Система роутинга (маршрутизация) в symfony 1.2

TRANSCRIPT

Page 1: Routing System In Symfony 1.2

Система роутинга в symfony 1.2

Alex [email protected] love Symfony for 2+ years

Page 2: Routing System In Symfony 1.2

['UA camp']

Кто я ? Люблю symfony уже 2+ года

Team lead of Lazy Ants (web2.0services.de)

Page 3: Routing System In Symfony 1.2

['UA camp']

О чем поговорим? Что такое роутинг и как его использовать

Как настраивать роутинг правила

Дополнительные возможности роутинга

Page 4: Routing System In Symfony 1.2

['UA camp']

Роутинг-класс это объект корневого уровня в

symfony 1.2

sfRoute

Page 5: Routing System In Symfony 1.2

['UA camp']

Объект роутинга включает в себя всю логику:

сопоставление URL генерация URL

Page 6: Routing System In Symfony 1.2

['UA camp']

Дополнительные параметры роута

method: PUT, POST, GET, …format: html, json, css, …host: имя хостаis_secure: https?request_uri: запрашиваемый URIprefix: Префикс добавляемый каждому с генерированному роуту

Page 7: Routing System In Symfony 1.2

['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%

Page 8: Routing System In Symfony 1.2

['UA camp']

Конфигурация роута по умолчанию

variable_prefixes: [':']'/article/$year/$month/$day/$title' вместо '/article/:year/:month/:day/:title'.

segment_separators: ['/', '.']'/article/:year-:month-:day/:title'

Page 9: Routing System In Symfony 1.2

['UA camp']

Конфигурация роута опции 1.2generate_shortest_url: генерация коротких URL, насколько это возможно

extra_parameters_as_query_string: генерация дополнительных параметров в виде запроса

Page 10: Routing System In Symfony 1.2

['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

Page 11: Routing System In Symfony 1.2

['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

Page 12: Routing System In Symfony 1.2

['UA camp']

Стандартные классы роутинга

sfRoutesfRequestRoutesfObjectRoutesfPropelRoute

Page 13: Routing System In Symfony 1.2

['UA camp']

Каждый роут, определенный в routing.yml, преобразуется в объект

класса sfRoute

article: url: /article/:id param: { module: article, action: index } class: myRoute

Page 14: Routing System In Symfony 1.2

['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'));

Page 15: Routing System In Symfony 1.2

['UA camp']

sf_method — нафиг нужен

/user/new + GET => user/new/user + GET => user/index

/user + POST => user/create

Page 16: Routing System In Symfony 1.2

['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

Page 17: Routing System In Symfony 1.2

['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(); }

Page 18: Routing System In Symfony 1.2

['UA camp']

sfObjectRoute — роуты как объектыclass psBlog extends BasepsBlog{ static public function getById($parameters) { return psBlogPeer::retrieveByPk($parameters['id']); }}

В шаблоне:<?php echo $post->getTitle() ?>

Page 19: Routing System In Symfony 1.2

['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(); }

Page 20: Routing System In Symfony 1.2

['UA camp']

sfPropelRoute связь роута модельюВ шаблоне:<?php foreach ($blog as $post): ?> <?php echo $post->getTitle() ?><br /><?php endforeach; ?>

Page 21: Routing System In Symfony 1.2

['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()) ?>

Page 22: Routing System In Symfony 1.2

['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]

Page 23: Routing System In Symfony 1.2

['UA camp']

class psBlog extends BasepsBlog{ public function getPostSlug() { return Blog::slugify($this->getTitle()); }}

Page 24: Routing System In Symfony 1.2

['UA camp']В шаблоне:<?php foreach ($blog as $post): ?> <?php echo link_to($post->getTitle(), 'post_slug', $post) ?><br /><?php endforeach; ?>

Page 25: Routing System In Symfony 1.2

['UA camp']

allow_empty: truehttp://../frontend_dev.php/post/3

Page 26: Routing System In Symfony 1.2

['UA camp']

Группа роутов

sfRouteCollectionsfObjectRouteCollectionsfPropelRouteCollection

Page 27: Routing System In Symfony 1.2

['UA camp']

sfPropelRouteCollection

blog: class: sfPropelRouteCollection options: { model: psBlog, module: Blog}

Page 28: Routing System In Symfony 1.2

['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

Page 29: Routing System In Symfony 1.2

['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: позволяет добавлять новые маршруты для объектов, роуты для акшинов, которые управляют списками

Page 30: Routing System In Symfony 1.2

['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,)

Page 31: Routing System In Symfony 1.2

['UA camp']

php symfony propel:generate-module-for-route

frontend blog

Page 32: Routing System In Symfony 1.2

['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) {}}

Page 33: Routing System In Symfony 1.2

['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/

Page 34: Routing System In Symfony 1.2

['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

Page 35: Routing System In Symfony 1.2

['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

Page 36: Routing System In Symfony 1.2

['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'); ?>

Page 37: Routing System In Symfony 1.2

['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

Page 38: Routing System In Symfony 1.2

['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>

Page 39: Routing System In Symfony 1.2

['UA camp']

symfony route без symfony

sfRoute это отдельный компопнент symfony Platform

http://pookey.co.uk/blog/archives/79-Playing-with-symfony-routing-without-symfony.html

Page 40: Routing System In Symfony 1.2

['UA camp']

Спасибо за внимание

Page 41: Routing System In Symfony 1.2

['UA camp']

Alex Demchenko

[email protected]

http://web2.0services.dehttp://lazy-ants.de