Routing System In Symfony 1.2

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

1 comments

Comments 1 - 1 of 1 previous next Post a comment

  • + ingvar Igor Brovchenko 6 months ago
    Отличная работа!!!!
    Мега спасибо :)
Post a comment
Embed Video
Edit your comment Cancel

1 Favorite

Routing System In Symfony 1.2 - Presentation Transcript

  1. Система роутинга в symfony 1.2 Alex Demchenko pilo.uanic@gmail.com I love Symfony for 2+ years
  2. ['UA camp'] Кто я ?  Люблю symfony уже 2+ года  Team lead of Lazy Ants (web2.0services.de)
  3. ['UA camp'] О чем поговорим?  Что такое роутинг и как его использовать  Как настраивать роутинг правила  Дополнительные возможности роутинга
  4. ['UA camp'] Роутинг-класс это объект корневого уровня в symfony 1.2 sfRoute
  5. ['UA camp'] Объект роутинга включает в себя всю логику:  сопоставление URL  генерация URL
  6. ['UA camp'] Дополнительные параметры роута method: PUT, POST, GET, … format: html, json, css, … host: имя хоста is_secure: https? request_uri: запрашиваемый URI prefix: Префикс добавляемый каждому с генерированному роуту
  7. ['UA camp'] Конфигурация роута по умолчанию frontend/config/factories.yml routing: 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%
  8. ['UA camp'] Конфигурация роута по умолчанию variable_prefixes: [':'] '/article/$year/$month/$day/$title' вместо '/article/:year/:month/:day/:title'. segment_separators: ['/', '.'] '/article/:year-:month-:day/:title'
  9. ['UA camp'] Конфигурация роута опции 1.2 generate_shortest_url: генерация коротких URL, насколько это возможно extra_parameters_as_query_string: генерация дополнительных параметров в виде запроса
  10. ['UA camp'] generate_shortest_url articles: 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
  11. ['UA camp'] extra_parameters_as_query_string articles: url: /articles options: { extra_parameters_as_query_string: true } echo url_for('@articles?page=1'); с генерирует /articles?page=1 и не будет совпадать с таким роутом в symfony 1.1
  12. ['UA camp'] Стандартные классы роутинга sfRoute sfRequestRoute sfObjectRoute sfPropelRoute
  13. ['UA camp'] Каждый роут, определенный в routing.yml, преобразуется в объект класса sfRoute article: url: /article/:id param: { module: article, action: index } class: myRoute
  14. ['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'));
  15. ['UA camp'] sf_method — нафиг нужен /user/new + GET => user/new /user + GET => user/index /user + POST => user/create
  16. ['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
  17. ['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(); }
  18. ['UA camp'] sfObjectRoute — роуты как объекты class psBlog extends BasepsBlog { static public function getById($parameters) { return psBlogPeer::retrieveByPk($parameters['id']); } } В шаблоне: <?php echo $post->getTitle() ?>
  19. ['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(); }
  20. ['UA camp'] sfPropelRoute связь роута моделью В шаблоне: <?php foreach ($blog as $post): ?> <?php echo $post->getTitle() ?><br /> <?php endforeach; ?>
  21. ['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()) ?>
  22. ['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]
  23. ['UA camp'] class psBlog extends BasepsBlog { public function getPostSlug() { return Blog::slugify($this->getTitle()); } }
  24. ['UA camp'] В шаблоне: <?php foreach ($blog as $post): ?> <?php echo link_to($post->getTitle(), 'post_slug', $post) ?> <br /> <?php endforeach; ?>
  25. ['UA camp'] allow_empty: true http://../frontend_dev.php/post/3
  26. ['UA camp'] Группа роутов sfRouteCollection sfObjectRouteCollection sfPropelRouteCollection
  27. ['UA camp'] sfPropelRouteCollection blog: class: sfPropelRouteCollection options: { model: psBlog, module: Blog}
  28. ['UA camp'] php symfony app:routes frontend list:  blog GET /blog.:sf_format new:  blog_new GET /blog/new.:sf_format create: blog_create POST  /blog.:sf_format edit:  blog_edit GET /blog/:id/edit.:sf_format update: blog_update PUT  /blog/:id.:sf_format delete: blog_delete DELETE /blog/:id.:sf_format 
  29. ['UA camp'] sfPropelRouteCollection — options  model: имя модели  actions: список экшенов из 7 доступных  module: имя модуля  prefix_path: префик к каждому роуту  column: имя поля primary key (id по умолчанию)  with_show: добалять метод show или нет  segment_names: другие имена для new и edit экшенов  model_methods: медоты для получения объектов  requirements: требования к параметрам  route_class: sfObjectRoute для sfObjectRouteCollection и sfPropelRoute для sfPropelRouteCollection  with_wildcard_routes: позволяет добавлять новые маршруты для объектов, роуты для акшинов, которые управляют списками
  30. ['UA camp'] php symfony app:routes frontend blog_new >> app Route \"blog_new\" for application \"frontend\" Name blog_new Pattern /blog/.:sf_format Class sfPropelRoute Defaults 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 $#x Tokens separator array (0 => '/',1 => NULL,) text array (0 => 'blog',1 => NULL,) separator array (0 => '/',1 => NULL,) text array (0 => '.:sf_format',1 => NULL,)
  31. ['UA camp'] php symfony propel:generate-module-for-route frontend blog
  32. ['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) {} }
  33. ['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/
  34. ['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
  35. ['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
  36. ['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'); ?>
  37. ['UA camp'] lazy_routes_deserialize app/config/factories.yml all: routing: class: sfPatternRouting param: generate_shortest_url: true extra_parameters_as_query_string: true lazy_routes_deserialize: true
  38. ['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>
  39. ['UA camp'] symfony route без symfony sfRoute это отдельный компопнент symfony Platform http://pookey.co.uk/blog/archives/79-Playing- with-symfony-routing-without-symfony.html
  40. ['UA camp'] Спасибо за внимание
  41. ['UA camp'] Alex Demchenko pilo.uanic@gmail.com http://web2.0services.de http://lazy-ants.de

+ Alex DemchenkoAlex Demchenko, 6 months ago

custom

1263 views, 1 favs, 2 embeds more stats

Система роутинга (маршрутиз more

More info about this document

© All Rights Reserved

Go to text version

  • Total Views 1263
    • 1134 on SlideShare
    • 129 from embeds
  • Comments 1
  • Favorites 1
  • Downloads 9
Most viewed embeds
  • 128 views on http://451f.com.ua
  • 1 views on http://feeds.feedburner.com

more

All embeds
  • 128 views on http://451f.com.ua
  • 1 views on http://feeds.feedburner.com

less

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

Cancel
File a copyright complaint
Having problems? Go to our helpdesk?

Categories