SlideShare une entreprise Scribd logo
1  sur  41
Télécharger pour lire hors ligne
Система роутинга в symfony 1.2




Alex Demchenko
pilo.uanic@gmail.com
I 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: запрашиваемый URI
prefix: Префикс добавляемый каждому
с генерированному роуту
['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:      '[wd_]+'
   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.2
generate_shortest_url: генерация коротких
URL, насколько это возможно

extra_parameters_as_query_string: генерация
дополнительных параметров в виде запроса
['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
['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
['UA camp']

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

         sfRoute
      sfRequestRoute
      sfObjectRoute
      sfPropelRoute
['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: true
http://../frontend_dev.php/post/3
['UA camp']

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


   sfRouteCollection
sfObjectRouteCollection
sfPropelRouteCollection
['UA camp']

        sfPropelRouteCollection

blog:
 class: sfPropelRouteCollection
 options: { model: psBlog, module: Blog}
['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

['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: позволяет добавлять новые маршруты
для объектов, роуты для акшинов, которые управляют
списками
['UA camp']
                                   php symfony app:routes frontend blog_new
>> app        Route quot;blog_newquot; for application quot;frontendquot;
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: '[wd_]+'
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,)
['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_deserialize
app/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.de
    http://lazy-ants.de

Contenu connexe

Tendances

Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien Potencier
 
Itsecteam shell
Itsecteam shellItsecteam shell
Itsecteam shellady36
 
6.Conocimiento cliente Cuenta Pagos en Linea. (Interlat Group
6.Conocimiento cliente Cuenta Pagos en Linea. (Interlat Group6.Conocimiento cliente Cuenta Pagos en Linea. (Interlat Group
6.Conocimiento cliente Cuenta Pagos en Linea. (Interlat GroupInterlat
 
Building Your First Widget
Building Your First WidgetBuilding Your First Widget
Building Your First WidgetChris Wilcoxson
 
WordPress 15th Meetup - Build a Theme
WordPress 15th Meetup - Build a ThemeWordPress 15th Meetup - Build a Theme
WordPress 15th Meetup - Build a ThemeFadi Nicolas Zahhar
 
Shortcodes In-Depth
Shortcodes In-DepthShortcodes In-Depth
Shortcodes In-DepthMicah Wood
 
Micropage in microtime using microframework
Micropage in microtime using microframeworkMicropage in microtime using microframework
Micropage in microtime using microframeworkRadek Benkel
 
PHP 102: Out with the Bad, In with the Good
PHP 102: Out with the Bad, In with the GoodPHP 102: Out with the Bad, In with the Good
PHP 102: Out with the Bad, In with the GoodJeremy Kendall
 
Componentization css angular
Componentization css angularComponentization css angular
Componentization css angularDavid Amend
 
Get into the FLOW with Extbase
Get into the FLOW with ExtbaseGet into the FLOW with Extbase
Get into the FLOW with ExtbaseJochen Rau
 
Contrail Project, OW2con11, Nov 24-25, Paris
Contrail Project, OW2con11, Nov 24-25, ParisContrail Project, OW2con11, Nov 24-25, Paris
Contrail Project, OW2con11, Nov 24-25, ParisOW2
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckAnthony Montalbano
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkDirk Haun
 
Clever Joomla! Templating Tips and Tricks
Clever Joomla! Templating Tips and TricksClever Joomla! Templating Tips and Tricks
Clever Joomla! Templating Tips and TricksThemePartner
 

Tendances (20)

Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
Itsecteam shell
Itsecteam shellItsecteam shell
Itsecteam shell
 
6.Conocimiento cliente Cuenta Pagos en Linea. (Interlat Group
6.Conocimiento cliente Cuenta Pagos en Linea. (Interlat Group6.Conocimiento cliente Cuenta Pagos en Linea. (Interlat Group
6.Conocimiento cliente Cuenta Pagos en Linea. (Interlat Group
 
Ubi comp27nov04
Ubi comp27nov04Ubi comp27nov04
Ubi comp27nov04
 
Building Your First Widget
Building Your First WidgetBuilding Your First Widget
Building Your First Widget
 
Wsomdp
WsomdpWsomdp
Wsomdp
 
Wp meetup custom post types
Wp meetup custom post typesWp meetup custom post types
Wp meetup custom post types
 
WordPress 15th Meetup - Build a Theme
WordPress 15th Meetup - Build a ThemeWordPress 15th Meetup - Build a Theme
WordPress 15th Meetup - Build a Theme
 
Shortcodes In-Depth
Shortcodes In-DepthShortcodes In-Depth
Shortcodes In-Depth
 
Micropage in microtime using microframework
Micropage in microtime using microframeworkMicropage in microtime using microframework
Micropage in microtime using microframework
 
Convidar para page !!
Convidar para page !!Convidar para page !!
Convidar para page !!
 
PHP 102: Out with the Bad, In with the Good
PHP 102: Out with the Bad, In with the GoodPHP 102: Out with the Bad, In with the Good
PHP 102: Out with the Bad, In with the Good
 
Componentization css angular
Componentization css angularComponentization css angular
Componentization css angular
 
Get into the FLOW with Extbase
Get into the FLOW with ExtbaseGet into the FLOW with Extbase
Get into the FLOW with Extbase
 
Contrail Project, OW2con11, Nov 24-25, Paris
Contrail Project, OW2con11, Nov 24-25, ParisContrail Project, OW2con11, Nov 24-25, Paris
Contrail Project, OW2con11, Nov 24-25, Paris
 
Codigo taller-plugins
Codigo taller-pluginsCodigo taller-plugins
Codigo taller-plugins
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages Suck
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application Framework
 
Clever Joomla! Templating Tips and Tricks
Clever Joomla! Templating Tips and TricksClever Joomla! Templating Tips and Tricks
Clever Joomla! Templating Tips and Tricks
 
Lettering js
Lettering jsLettering js
Lettering js
 

En vedette

Auto deploy symfony app with codeship and elastic beanstalk
Auto deploy symfony app with codeship and elastic beanstalkAuto deploy symfony app with codeship and elastic beanstalk
Auto deploy symfony app with codeship and elastic beanstalkAlex Demchenko
 
Google map markers with Symfony2
Google map markers with Symfony2Google map markers with Symfony2
Google map markers with Symfony2DevOWL Meetup
 
Symfony Project Publication
Symfony Project PublicationSymfony Project Publication
Symfony Project PublicationAlex Demchenko
 
Symfony camp ua 2010 stats
Symfony camp ua 2010 statsSymfony camp ua 2010 stats
Symfony camp ua 2010 statsAlex Demchenko
 
Google Map маркеры вместе с Symfony2
Google Map маркеры вместе с Symfony2Google Map маркеры вместе с Symfony2
Google Map маркеры вместе с Symfony2Aliaksandr Harbunou
 
Symfony as the platform for open source projects (sympal, apostrophe, diem)
Symfony as the platform for open source projects (sympal, apostrophe, diem)Symfony as the platform for open source projects (sympal, apostrophe, diem)
Symfony as the platform for open source projects (sympal, apostrophe, diem)Alex Demchenko
 

En vedette (9)

Auto deploy symfony app with codeship and elastic beanstalk
Auto deploy symfony app with codeship and elastic beanstalkAuto deploy symfony app with codeship and elastic beanstalk
Auto deploy symfony app with codeship and elastic beanstalk
 
Symfony2 start
Symfony2 startSymfony2 start
Symfony2 start
 
Google map markers with Symfony2
Google map markers with Symfony2Google map markers with Symfony2
Google map markers with Symfony2
 
Twig, что за..
Twig, что за..Twig, что за..
Twig, что за..
 
Symfony Project Publication
Symfony Project PublicationSymfony Project Publication
Symfony Project Publication
 
Symfony camp ua 2010 stats
Symfony camp ua 2010 statsSymfony camp ua 2010 stats
Symfony camp ua 2010 stats
 
Symfony2 – reload?
Symfony2 – reload?Symfony2 – reload?
Symfony2 – reload?
 
Google Map маркеры вместе с Symfony2
Google Map маркеры вместе с Symfony2Google Map маркеры вместе с Symfony2
Google Map маркеры вместе с Symfony2
 
Symfony as the platform for open source projects (sympal, apostrophe, diem)
Symfony as the platform for open source projects (sympal, apostrophe, diem)Symfony as the platform for open source projects (sympal, apostrophe, diem)
Symfony as the platform for open source projects (sympal, apostrophe, diem)
 

Similaire à Routing System In Symfony 1.2

Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4Javier Eguiluz
 
And the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack SupportAnd the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack SupportBen Scofield
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosIgor Sobreira
 
Quality Use Of Plugin
Quality Use Of PluginQuality Use Of Plugin
Quality Use Of PluginYasuo Harada
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐいHisateru Tanaka
 
How I Built a Power Debugger Out of the Standard Library and Things I Found o...
How I Built a Power Debugger Out of the Standard Library and Things I Found o...How I Built a Power Debugger Out of the Standard Library and Things I Found o...
How I Built a Power Debugger Out of the Standard Library and Things I Found o...doughellmann
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)Jeff Eaton
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On RailsWen-Tien Chang
 
シックス・アパート・フレームワーク
シックス・アパート・フレームワークシックス・アパート・フレームワーク
シックス・アパート・フレームワークTakatsugu Shigeta
 
More Secrets of JavaScript Libraries
More Secrets of JavaScript LibrariesMore Secrets of JavaScript Libraries
More Secrets of JavaScript Librariesjeresig
 
Laravel5 Introduction and essentials
Laravel5 Introduction and essentialsLaravel5 Introduction and essentials
Laravel5 Introduction and essentialsPramod Kadam
 
Hacking ansible
Hacking ansibleHacking ansible
Hacking ansiblebcoca
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2RORLAB
 

Similaire à Routing System In Symfony 1.2 (20)

Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4
 
Django
DjangoDjango
Django
 
And the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack SupportAnd the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack Support
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazos
 
Quality Use Of Plugin
Quality Use Of PluginQuality Use Of Plugin
Quality Use Of Plugin
 
WordPress APIs
WordPress APIsWordPress APIs
WordPress APIs
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
How I Built a Power Debugger Out of the Standard Library and Things I Found o...
How I Built a Power Debugger Out of the Standard Library and Things I Found o...How I Built a Power Debugger Out of the Standard Library and Things I Found o...
How I Built a Power Debugger Out of the Standard Library and Things I Found o...
 
Test upload
Test uploadTest upload
Test upload
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
 
PhpBB meets Symfony2
PhpBB meets Symfony2PhpBB meets Symfony2
PhpBB meets Symfony2
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On Rails
 
シックス・アパート・フレームワーク
シックス・アパート・フレームワークシックス・アパート・フレームワーク
シックス・アパート・フレームワーク
 
More Secrets of JavaScript Libraries
More Secrets of JavaScript LibrariesMore Secrets of JavaScript Libraries
More Secrets of JavaScript Libraries
 
Send.php
Send.phpSend.php
Send.php
 
Merb jQuery
Merb jQueryMerb jQuery
Merb jQuery
 
Laravel5 Introduction and essentials
Laravel5 Introduction and essentialsLaravel5 Introduction and essentials
Laravel5 Introduction and essentials
 
Django Vs Rails
Django Vs RailsDjango Vs Rails
Django Vs Rails
 
Hacking ansible
Hacking ansibleHacking ansible
Hacking ansible
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2
 

Dernier

Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...JeylaisaManabat1
 
E J Waggoner against Kellogg's Pantheism 8.pptx
E J Waggoner against Kellogg's Pantheism 8.pptxE J Waggoner against Kellogg's Pantheism 8.pptx
E J Waggoner against Kellogg's Pantheism 8.pptxJackieSparrow3
 
南新罕布什尔大学毕业证学位证成绩单-学历认证
南新罕布什尔大学毕业证学位证成绩单-学历认证南新罕布什尔大学毕业证学位证成绩单-学历认证
南新罕布什尔大学毕业证学位证成绩单-学历认证kbdhl05e
 
Inspiring Through Words Power of Inspiration.pptx
Inspiring Through Words Power of Inspiration.pptxInspiring Through Words Power of Inspiration.pptx
Inspiring Through Words Power of Inspiration.pptxShubham Rawat
 
(南达科他州立大学毕业证学位证成绩单-永久存档)
(南达科他州立大学毕业证学位证成绩单-永久存档)(南达科他州立大学毕业证学位证成绩单-永久存档)
(南达科他州立大学毕业证学位证成绩单-永久存档)oannq
 
Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...
Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...
Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...Authentic No 1 Amil Baba In Pakistan
 

Dernier (6)

Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
 
E J Waggoner against Kellogg's Pantheism 8.pptx
E J Waggoner against Kellogg's Pantheism 8.pptxE J Waggoner against Kellogg's Pantheism 8.pptx
E J Waggoner against Kellogg's Pantheism 8.pptx
 
南新罕布什尔大学毕业证学位证成绩单-学历认证
南新罕布什尔大学毕业证学位证成绩单-学历认证南新罕布什尔大学毕业证学位证成绩单-学历认证
南新罕布什尔大学毕业证学位证成绩单-学历认证
 
Inspiring Through Words Power of Inspiration.pptx
Inspiring Through Words Power of Inspiration.pptxInspiring Through Words Power of Inspiration.pptx
Inspiring Through Words Power of Inspiration.pptx
 
(南达科他州立大学毕业证学位证成绩单-永久存档)
(南达科他州立大学毕业证学位证成绩单-永久存档)(南达科他州立大学毕业证学位证成绩单-永久存档)
(南达科他州立大学毕业证学位证成绩单-永久存档)
 
Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...
Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...
Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...
 

Routing System In Symfony 1.2

  • 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: '[wd_]+' 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 quot;blog_newquot; for application quot;frontendquot; 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: '[wd_]+' 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
  • 41. ['UA camp'] Alex Demchenko pilo.uanic@gmail.com http://web2.0services.de http://lazy-ants.de