Symfony Documentation - files.abradabra.comfiles.abradabra.com/books/Symfony2_ru.pdf · Symfony...
-
Upload
phungthien -
Category
Documents
-
view
324 -
download
0
Transcript of Symfony Documentation - files.abradabra.comfiles.abradabra.com/books/Symfony2_ru.pdf · Symfony...
-
Symfony Documentation
2.0
Fabien Potencier
15 January 2012
-
I 1
1 5
II 7
2 112.1 Symfony2 HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . 112.2 Symfony2 PHP . . . . . . . . . . . . . . . . . . . . . . . . 222.3 Symfony2 . . . . . . . . . . . . . . . . . . . . . . . 372.4 Symfony2 . . . . . . . . . . . . . . . . . . . . . . . . . 422.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 752.7 . . . . . . . . . . . . . . . . . . . . . 982.8 Doctrine () . . . . . . . . . . . . . . . . . . . . . . 1212.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1482.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1622.11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1792.12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2102.13 HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2472.14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2672.15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2832.16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3042.17 API Symfony2 . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
i
-
III 329
3 Cookbook 3313.1 Symfony2 git- . . . . 3313.2 . . . . . . . . . . . . . . . . . 3343.3 . . . . . . . . . . . . . 3363.4 HTTPS HTTP . 3373.5 . . . . . . . . . . . . . . . . . . . . . 3383.6 Gmail . . . . . . . . 3413.7 HTTP . . 3423.8 . . . . . . . . 3423.9 . . . . . . . 3433.10 Varnish . . . . . . . . . . 3453.11 (.. ) . 3463.12 PHP Twig . . . . . . . . . . . . . . . . 3473.13 Monolog . . . . . . . . . . . . . . 3523.14 . . . . . . . . . . . . . . . . . . . . 3563.15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
IV 367
4 Reference Documents 3714.1 . . . . . . . . . . . . . . . . . . . . . . 3714.2 Twig . . . . . . . . . . . . . 3754.3 Dependency Injection . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
V 387
5 Symfony SE Bundles 391
VI 393
6 3976.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3976.2 . . . . . . . . . . . . . . . . . . . . . . . . . . 4006.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
405
ii
-
I
1
-
Symfony Documentation, 2.0
Symfony2 :
3
-
Symfony Documentation, 2.0
4
-
1
Symfony2:
quick_tour/the_big_picture >
quick_tour/the_view >
quick_tour/the_controller >
quick_tour/the_architecture
5
-
Symfony Documentation, 2.0
6 1.
-
II
7
-
Symfony Documentation, 2.0
Symfony2 :
9
-
Symfony Documentation, 2.0
10
-
2
2.1 Symfony2 HTTP
! Symfony2, , , - ( - ). Symfony2 , , - , , , . Symfony , : , - . , Symfony, web, , - PHP- Symfony2 ., .
Symfony2, , web-: HTTP. , .
2.1.1 HTTP
HTTP (Hypertext Transfer Protocol ) - , . ! , xkcd, () :
11
http://xkcd.com/ -
Symfony Documentation, 2.0
, , - . HTTP - , . , web, - .
Symfony2 . , HTTP - , . Symfony2 , .
1:
. - , - ( iPhone ..) , HTTP. , .
() -xkcd:
HTTP :
12 2.
-
Symfony Documentation, 2.0
GET / HTTP/1.1
Host: xkcd.com
Accept: text/html
User-Agent: Mozilla/5.0 (Macintosh)
, . HTTP - - 2 : URI HTTP-.
URI ( /, /contact, ..) - , - . HTTP- ( GET) , . HTTP , :
GET POST PUT DELETE
HTTP-, , HTTP- :
DELETE /blog/15 HTTP/1.1
: HTTP-, HTTP, . , - PUT DELETE.
, HTTP- - , (headers). - , Host, , - (Accept) , (User-Agent). , - List of HTTP header elds.
2:
, , ( URI) - HTTP-. , GET-, HTTP-. web xkcd:
2.1. Symfony2 HTTP 13
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields -
Symfony Documentation, 2.0
HTTP, , , - :
HTTP/1.1 200 OK
Date: Sat, 02 Apr 2011 21:05:05 GMT
Server: lighttpd/1.4.19
Content-Type: text/html
HTTP- ( HTML- -), . - HTTP - ( 200). - - , . ? ? - , - , , - ( ). Listof HTTP status codes .
, HTTP- , - HTTP-. , HTTP- Content-Type. , HTML, XML JSON. Content-Type - , .
, . , .
14 2.
http://en.wikipedia.org/wiki/List_of_HTTP_status_codeshttp://en.wikipedia.org/wiki/List_of_HTTP_status_codes -
Symfony Documentation, 2.0
, Web-
- - , - . , .
: , , (web, , JSONAPI) , .
Symfony .
: HTTP, - HTTP 1.1 RFC HTTP Bis, . - - Firefox Live HTTP Headers.
2.1.2 PHP
PHP? PHP :
-
Symfony Documentation, 2.0
The URI requested is: /testing?foo=symfony
The value of the "foo" parameter is: symfony
2.1.3 Symfony
Symfony PHP , HTTP- - . Symfony\Component\HttpFoundation\Request - - HTTP-. - :
-
Symfony Documentation, 2.0
$response->headers->set('Content-Type', 'text/html');
// prints the HTTP headers followed by the content$response->send();
Symfony , - - . Symfony, , , ,
: Request Response HttpFoundation. Symfony .
2.1.4
HTTP-, Request Response . - , - . , , ( ).
, , email', - , - , HTML- . ?
Symfony , , .
-
, :
index.php
contact.php
blog.php
, URL ( blog.php news.php ?),
2.1. Symfony2 HTTP 17
-
Symfony Documentation, 2.0
, , .
front controller, PHP-, . :
/index.php index.php/index.php/contact index.php/index.php/blog index.php
: mod_rewrite Apache ( - web-) URL -, .. - /, /contact /blog.
, . URL PHP- - - - , - URL. , -. , WordPress.
, -. , - ? URI - , . :
-
Symfony Documentation, 2.0
Symfony
Symfony , . Symfony :
. 2.1: -, Response.
-, URL PHP-. - , controller, - , Symfony, Response. , : .
! - :
-;
, PHP- , -, ;
, - Response.
Symfony Request
, . -, /contact Symfony . -, /contact URI:
2.1. Symfony2 HTTP 19
-
Symfony Documentation, 2.0
contact:
pattern: /contact
defaults: { _controller: AcmeDemoBundle:Main:contact }
: YAML - . - XML PHP.
- /contact, URI - . , AcmeDemoBundle:Main:contact , contactAction, MainController:
-
Symfony Documentation, 2.0
: Symfony2
Symfony2? , Symfony2 - - 20 , PHP-. , Symfony2 Components, - , . :
HttpFoundation - Request Response, - ;
Routing - , - URI ( /contact) , ( contactAction());
Form - ;
Validator - , - - , ;
ClassLoader - , PHP- - require , .
Templating - , - (, aka layout), (escaping, , ..);
Security -;
Translation - .
PHP-, Symfony2.
: Symfony2 Framework
- Symfony2 Framework? Symfony2 Framework PHP -, 2 :
1. (Symfony2 Components) ( Swiftmailer );
2. , .
2.1. Symfony2 HTTP 21
https://github.com/symfony/HttpFoundationhttps://github.com/symfony/Routinghttps://github.com/symfony/Formhttps://github.com/symfony/Validatorhttps://github.com/symfony/ClassLoaderhttps://github.com/symfony/Templatinghttps://github.com/symfony/Securityhttps://github.com/symfony/Translation -
Symfony Documentation, 2.0
- . Symfony Bundle (), .
Symfony2 web-, . - , Symfony2, . ... ! )
2.2 Symfony2 PHP
Symfony2 , PHP , ?
PHP-, - Model-View-Controller ( MVC) Symfony2, ! , Symfony2 , - PHP, .
, PHP . , - web- PHP .
, , Symfony2 .
2.2.1 PHP
- , PHP. , , , . PHP :
22 2.
-
Symfony Documentation, 2.0
List of Posts
List of Posts
-
Symfony Documentation, 2.0
, HTML - - :
, , - index.php - . controller - , ,
24 2.
-
Symfony Documentation, 2.0
. , , - .
, , . , , ( list.json.php JSON-).
()
. , , ? , - model.php:
-
Symfony Documentation, 2.0
: model.php - . - ( ). , , ( ).
(index.php) :
(templates/list.php) , - :
List of Posts
26 2.
-
Symfony Documentation, 2.0
, -layout. , , PHP- (ob_start(), ob_get_clean()) .Symfony2 Templating, . - .
2.2.2 show
list , - . , - , show, - - id.
, model.php, id:
, , show.php - :
2.2. Symfony2 PHP 27
-
Symfony Documentation, 2.0
, - . , , . , id . , 404, . - id mysql_real_escape_string() - SQL-.
, - model.php. - (, )? , - . - , , ...
2.2.3 Front Controller
front controller : - PHP-, . frontcontroller ( -) URI , :
-
/index.php => ( index.php)
/show.php => ( show.php)
index.php -
/index.php => ( index.php)
/index.php/show => ( index.php)
: URI, index.php, , - rewrite rules - Apache ( -). URI /show.
-, PHP (index.php ) . /index.php/show -
28 2.
-
Symfony Documentation, 2.0
index.php, , URI. - - .
-
! -. , , , , , , -, . index.php , , - URI :
-
Symfony Documentation, 2.0
require 'templates/show.php';
}
- index.php , - , ( list_action() show_action()). , - , , , Symfony2.
: - - URL. , URL , , - /show /read, . . Symfony2 URL .
, PHP- , . , . , - , list (/index.php) / ( Apache rewrite rules). , , (-, , , ..). , , , - . ?
Symfony2
Symfony2 . , Symfony2, PHP Symfony2. , Symfony. - , - PHP-, .
-, symfony vendor/symfony/. , app/bootstrap.php. (require) :
-
Symfony Documentation, 2.0
$loader->registerNamespaces(array(
'Symfony' => __DIR__.'/vendor/symfony/src',
));
$loader->register();
, Symfony. Symfony, require , - .
Symfony , - - . Symfony2 : Symfony\Component\HttpFoundation\Request Symfony\Component\HttpFoundation\Response. - HTTP-, HTTP-, . :
-
Symfony Documentation, 2.0
use Symfony\Component\HttpFoundation\Response;
function list_action()
{
$posts = get_all_posts();
$html = render_template('templates/list.php', array('posts' => $posts));
return new Response($html);
}
function show_action($id)
{
$post = get_post_by_id($id);
$html = render_template('templates/show.php', array('post' => $post));
return new Response($html);
}
// - function render_template($path, array $args)
{
extract($args);
ob_start();
require $path;
$html = ob_get_clean();
return $html;
}
Symfony2, -. Request . , getPathInfo() URI ( /show /index.php/show). , - /index.php/show, show_action().
Response HTTP-, - HTTP -. , , .
Symfony2
, . , - , ob_start() ob_get_clean() ., - , -
32 2.
-
Symfony Documentation, 2.0
, Symfony - Routing Templating, .
, Symfony2 . , Symfony2:
2.2. Symfony2 PHP 33
https://github.com/symfony/Routinghttps://github.com/symfony/Templating -
Symfony Documentation, 2.0
List of Posts
: show -, list.
Symfony2 ( Kernel - ) , - , - , . - :
# app/config/routing.ymlblog_list:
pattern: /blog
defaults: { _controller: AcmeBlogBundle:Blog:list }
blog_show:
pattern: /blog/show/{id}
defaults: { _controller: AcmeBlogBundle:Blog:show }
, Symfony2 , - . , ( Symfony2, !):
34 2.
-
Symfony Documentation, 2.0
-
Symfony Documentation, 2.0
! Symfony2Bundles.org
2.2.4
Symfony2, Twig, - . , ! , , , Twig:
{# src/Acme/BlogBundle/Resources/views/Blog/list.html.twig #}
{% extends "::layout.html.twig" %}{% block title %} List of Posts{% endblock %}
{% block body %}List of Posts
{% for post in posts %}
{{ post.title }}
{% endfor %}
{% endblock %}
layout.html.twig :
{# app/Resources/views/layout.html.twig #}
{% block title %} Default title{% endblock %}
{% block body %} {% endblock %}
Twig Symfony2. , PHP Symfony2, Twig. Twig .
36 2.
http://symfony2bundles.orghttp://twig.sensiolabs.org -
Symfony Documentation, 2.0
2.2.5 Cookbook
PHP Twig
2.3 Symfony2
, Symfony. , Symfony , - , .
: , .
2.3.1 Symfony2
: , , Web-(, Apache) PHP 5.3.2 . - Symfony2 .
Symfony2 , Symfony2, (Bundles), - . Symfony2, , - .
Symfony2 http://symfony.com/download. Symfony Standard Edition, . 2 :
.tgz .zip - , -.
, - (with/without vendors). Git, Symfony2 without vendors, /.
2.3. Symfony2 37
http://symfony.com/downloadhttp://git-scm.com/ -
Symfony Documentation, 2.0
root- web- - . UNIX ( ### ):
# for .tgz filetar zxvf Symfony_Standard_Vendors_2.0.###.tgz
# for a .zip fileunzip Symfony_Standard_Vendors_2.0.###.zip
, Symfony/, :
www/
-
Symfony Documentation, 2.0
Symfony2 -, , PHP Symfony. URL :
http://localhost/Symfony/web/config.php
- - , - .
2.3. Symfony2 39
-
Symfony Documentation, 2.0
, app/cache app/logs -, -, . UNIX-, , - - , , , . www-data - yourname - :1. ACL , chmod +a chmod +a. - , - :
rm -rf app/cache/*
rm -rf app/logs/*
sudo chmod +a "www-data allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
sudo chmod +a "yourname allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
2. Acl , chmod +a chmod +a, ,setfacl. , ACL - setfacl ( ,, Ubuntu):
sudo setfacl -R -m u:www-data:rwx -m u:yourname:rwx app/cache app/logs
sudo setfacl -dR -m u:www-data:rwx -m u:yourname:rwx app/cache app/logs
3. ACL ACL , umask , cache log (world-writable) - - . - app/console, web/app.php web/app_dev.php:
umask(0002); // 0775
//
umask(0000); // 0777
, ACL , , umask thread-safe.
, Go to theWelcome page Symfony2:
40 2.
https://help.ubuntu.com/community/FilePermissions#ACLs -
Symfony Documentation, 2.0
http://localhost/Symfony/web/app_dev.php/
Symfony2 !!
2.3.2
, Symfony2 , -. - README.rst ( ) , .
Symfony, Symfony2 , , , - .
2.3.3
Git Subversion, .Symfony Standard - .
, git, : Symfony2 git-.
2.3. Symfony2 41
-
Symfony Documentation, 2.0
vendor/
vendor/ . Git , .gitignore :
vendor/
vendor . (-!), - php bin/vendors install .
2.4 Symfony2
Symfony2 , 2 :
: URL ( /about) , (PHP ), Symfony2 -, URL ;
: PHP , - Response, .
, , Web. - Web HTTP . - .
Symfony2 , .
? !
2.4.1 Hello Symfony!
Hello World!. , , ( Hello Symfony), URL:
http://localhost/app_dev.php/hello/Symfony
Symfony . .
42 2.
-
Symfony Documentation, 2.0
: , Symfony2 - -. URL, , , localhost web- Symfony2 . , , . - Symfony2 .
: (bundle)
, (bundle). Symfony2 - plugin, , .
, , - - , PHP-, Javascript (. ).
AcmeHelloBundle (-, ), - , ( -):
php app/console generate:bundle --namespace=Acme/HelloBundle --format=yml
: src/Acme/HelloBundle. app/AppKernel.php - , :
-
Symfony Documentation, 2.0
1:
, Symfony2, app/config/routing.yml. , Symfony2, XML PHP .
, , Symfony AcmeHelloBundle:
YAML
# app/config/routing.ymlAcmeHelloBundle:
resource: "@AcmeHelloBundle/Resources/config/routing.yml"
prefix: /
XML
PHP
-
Symfony Documentation, 2.0
app/config/routing.yml - .
, routing.yml , , URL , :
YAML
# src/Acme/HelloBundle/Resources/config/routing.ymlhello:
pattern: /hello/{name}
defaults: { _controller: AcmeHelloBundle:Hello:index }
XML
AcmeHelloBundle:Hello:index
PHP
-
Symfony Documentation, 2.0
: URL . - .
2:
URI /hello/Ryan , hello AcmeHelloBundle:Hello:index. .
AcmeHelloBundle:Hello:index - - indexAction PHP-, Acme\HelloBundle\Controller\Hello. - AcmeHelloBundle:
-
Symfony Documentation, 2.0
}
}
: Response, , ( HTML-, ).
! , ! , :
http://localhost/app_dev.php/hello/Ryan
: (prod) -, URL:
http://localhost/app.php/hello/Ryan
, , :
php app/console cache:clear --env=prod --no-debug
(, , ) .
: . .
3:
(HTML , ) - . , :
1
-
Symfony Documentation, 2.0
9 {
10 public function indexAction($name)
11 {
12 return $this->render('AcmeHelloBundle:Hello:index.html.twig', array('name' => $name));
13
14 // render a PHP template instead15 // return $this->render('AcmeHelloBundle:Hello:index.html.php', array('name' => $name));16 }
17 }
: , render(), - Symfony\Bundle\FrameworkBundle\Controller\Controller (APIdocs: Symfony\Bundle\FrameworkBundle\Controller\Controller), . use 6, , Controller 8.
render() Response, (-) . , , , Response.
, .Symfony2 , 2 : PHP- , Twig. , , .
AcmeHelloBundle:Hello:index.html.twig, :
BundleName:ControllerName:TemplateName
, , , - :
///BundleName/Resources/views/ControllerName/TemplateName
AcmeHelloBundle - , Hello - index.html.twig - :
Twig
1 {# src/Acme/HelloBundle/Resources/views/Hello/index.html.twig #}2 {% extends '::base.html.twig' %}3
4 {% block body %}5 Hello {{ name }} !6 {% endblock %}
48 2.
http://twig.sensiolabs.org -
Symfony Documentation, 2.0
PHP
Hello !
Twig:
2 : extends . , (layout) .
4 : block , body. , (base.html.twig) body.
, ::base.html.twig, , ( (::)). , app:
Twig
{# app/Resources/views/base.html.twig #}
{% block title %} Welcome!{% endblock %} {% block stylesheets %} {% endblock %}
{% block body %} {% endblock %}{% block javascripts %} {% endblock %}
PHP
-
Symfony Documentation, 2.0
HTML- body, index.html.twig. title - , - Welcome!.
. HTML , CSS- .
, - . , - Response. , , - Response.
2.4.2
Symfony2. , Symfony2. , . , !
Symfony (application), , ( ) :
app/: ;
src/: PHP ;
vendor/: ;
web/: , web- ;
Web
Web- - , , JavaScript . - (front controller):
-
Symfony Documentation, 2.0
require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
use Symfony\Component\HttpFoundation\Request;
$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$kernel->handle(Request::createFromGlobals())->send();
- ( app.php)- PHP , -, Symfony2 - Kernel-(AppKernel), .
: - - URL, , PHP-. -, URL :
http://localhost/app.php/hello/Ryan
- app.php : URL /hello/Ryan - . - mod_rewrite Apache ( URL) app.php, URL:
http://localhost/hello/Ryan
- , . , ().
(app)
-, AppKernel - . , app/.
, , Symfony . - , .
registerBundles(): , (. );
registerContainerConfiguration(): (. ).
2.4. Symfony2 51
-
Symfony Documentation, 2.0
app/ , - app/config/(. ). app/ (app/cache), - (app/logs) (app/Resources). .
: app/autoload.php. src/ vendor/. , include require. , Symfony2 , , . , src/. , - :
Class Name:
Acme\HelloBundle\Controller\HelloController
Path:
src/Acme/HelloBundle/Controller/HelloController.php
, , app/autoload.php - - vendor/. , .
(src)
, src/ (PHP-,, , ..). , , .
(bundle)?
2.4.3
- , . , Symfony2, . Symfony2. - , symfony2bundles.org.
52 2.
http://symfony2bundles.org/ -
Symfony Documentation, 2.0
. , .
: , .
, . BlogBundle ForumBundle ( - ). , PHP , , , , - . .
, registerBundles() - AppKernel:
-
Symfony Documentation, 2.0
: , , (app/autoload.php) , -.
Symfony Standard Edition . -, .
, , , - AcmeTestBundle .
: Acme - , - , (ABCTestBundle ABC).
, src/Acme/TestBundle/ AcmeTestBundle.php:
-
Symfony Documentation, 2.0
public function registerBundles()
{
$bundles = array(
// ...
// register your bundlesnew Acme\TestBundle\AcmeTestBundle(),
);
// ...
return $bundles;
}
, , AcmeTestBundle .
Symfony :
php app/console generate:bundle --namespace=Acme/TestBundle
, , - . .
: , , -, registerBundles(). generate:bundle - .
. , - , Symfony2. AcmeHelloBundle, :
Controller/ ( HelloController.php);
Resources/config/ , ( routing.yml);
Resources/views/ , (Hello/index.html.twig);
Resources/public/ (, . . . ), web/ assets:install;
Tests/ .
2.4. Symfony2 55
-
Symfony Documentation, 2.0
, , . , .
, , , , . .
2.4.4
, . -, YAML, XML PHP. , app/config/ config.yml, config.xml config.php, :
YAML
# app/config/config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
framework:
secret: %secret%
charset: UTF-8
router: { resource: "%kernel.root_dir%/config/routing.yml" }
form: true
csrf_protection: true
validation: { enable_annotations: true }
templating: { engines: ['twig'] } #assets_version: SomeVersionScheme
session:
default_locale: %locale%
auto_start: true
# Twig Configuration
twig:
debug: %kernel.debug%
strict_variables: %kernel.debug%
# ...
XML
56 2.
-
Symfony Documentation, 2.0
PHP
-
Symfony Documentation, 2.0
// ...
: , / - - .
, framework twig, - . , framework SymfonyFrameworkBundle , - .
. . .
(YAML, XML and PHP). -. :
YAML: , ; XML: , YAML, IDE XML;
PHP : , , - .
2.4.5
. - PHP ( -), . , dev -, prod . dev , prod . , .
Symfony2 (dev, test prod), . - - . - dev , app_dev.php:
http://localhost/app_dev.php/hello/Ryan
, , - prod:
58 2.
-
Symfony Documentation, 2.0
http://localhost/app.php/hello/Ryan
prod , , - Twig PHP . , :
php app/console cache:clear --env=prod --no-debug
: web/app.php, , prod :
$kernel = new AppKernel('prod', false);
- prod .
: (test) . .
AppKernel :
-
Symfony Documentation, 2.0
framework:
router: { resource: "%kernel.root_dir%/config/routing_dev.yml" }
profiler: { only_exceptions: false }
# ...
XML
PHP
-
Symfony Documentation, 2.0
2.4.6
! Symfony2 , - . , , :
, , () ;
4 : web/ ( -), app/ (), src/ ( ), vendor/ (- ) ( bin/ );
Symfony2 ( ) , , ;
app/config YAML, XML PHP;
- (app.php app_dev.php) ;
, . Symfony2, .
2.5
- PHP-, , HTTP HTTP Response. - HTML , XML-, JSON-, -, , 404, , . , , .
, , Symfony2 . , - Hello world!:
-
Symfony Documentation, 2.0
return new Response('Hello world!');
}
: Response. , , , email . , , Response, .
, ! :
A Response, - .
B slug , Response, . slug , Response - 404 ( ).
C . - , . , Response, thank you.
2.5.1 --
, Symfony2, - . , , :
1. - ( app.php app_dev.php), ;
2. Router (URI ), - _controller ;
3. , , - Response;
4. HTTP- Response , - .
- (#3) , URL (#2).
: - - , -
62 2.
-
Symfony Documentation, 2.0
. - - PHP-, web- . - (prod, app.php) (dev, app_dev.php). - - .
2.5.2
PHP-, (, , (Closure)), Symfony2 - . (actions).
1
-
Symfony Documentation, 2.0
line 10 : Action - (index). , URI . - {name} - ($name).
line 12 : Response.
2.5.3 URL
HTML-. , , - URL :
YAML
# app/config/routing.ymlhello:
pattern: /hello/{name}
defaults: { _controller: AcmeHelloBundle:Hello:index }
XML
AcmeHelloBundle:Hello:index
PHP
// app/config/routing.php$collection->add('hello', new Route('/hello/{name}', array(
'_controller' => 'AcmeHelloBundle:Hello:index',
)));
URI /hello/ryan HelloController::indexAction() $name ryan. .
, -: AcmeHelloBundle:Hello:index. Symfony2 . - Symfony2 HelloController AcmeHelloBundle. indexAction().
, : .
64 2.
-
Symfony Documentation, 2.0
: - app/config/. , - , . - : .
: .
, _controller AcmeHelloBundle:Hello:index HelloController::indexAction(), AcmeHelloBundle. , :
-
Symfony Documentation, 2.0
AcmeHelloBundle:Hello:index
green
PHP
-
Symfony Documentation, 2.0
-
Symfony Documentation, 2.0
2.5.4
Symfony2 Controller, - , . - Controller -.
use HelloController, Controller:
-
Symfony Documentation, 2.0
2.5.5 ,
, , - . , ,, , Symfony2 - .
(redirecting)
, redirect():
-
Symfony Documentation, 2.0
, (forwarding)
, forward(). , - , . forward() Response, -, :
-
Symfony Documentation, 2.0
$response = $httpKernel->forward('AcmeHelloBundle:Hello:fancy', array(
'name' => $name,
'color' => 'green',
));
, () , HTML ( ) . renderView() . Response:
-
Symfony Documentation, 2.0
$router = $this->get('router');
$mailer = $this->get('mailer');
Symfony2 - . , container:debug:
php app/console container:debug
Service container .
2.5.6 404
- , - 404. , . - , :
-
Symfony Documentation, 2.0
-) . , Symfony2 (cookie), PHP.
-:
$session = $this->getRequest()->getSession();
// store an attribute for reuse during a later user request$session->set('foo', 'bar');
// in another controller for another request$foo = $session->get('foo');
// set the user locale$session->setLocale('fr');
, .
Flash-
, - . : . ash-.
, , :
-
Symfony Documentation, 2.0
.
- notice:
Twig
{% if app.session.hasFlash('notice') %}
{{ app.session.flash('notice') }}
{% endif %}
PHP
, ash- . , .
2.5.8
- Response. Symfony\Component\HttpFoundation\Response PHP-HTTP- - , HTTP- , - :
// Response - 200 ( )$response = new Response('Hello '.$name, 200);
// JSON- - 2000$response = new Response(json_encode(array('name' => $name)));
$response->headers->set('Content-Type', 'application/json');
: headers - Symfony\Component\HttpFoundation\HeaderBag, - Response. , Content-Type, content-type content_type -.
74 2.
-
Symfony Documentation, 2.0
2.5.9
, Request, Controller:
$request = $this->getRequest();
$request->isXmlHttpRequest(); // is it an Ajax request?
$request->getPreferredLanguage(array('en', 'fr'));
$request->query->get('page'); // get a $_GET parameter
$request->request->get('page'); // get a $_POST parameter
Response, HeaderBag .
2.5.10
, , . Symfony , - PHP-, Response, .
, , Controller, , ., HTML - render() .
, , .
2.5.11 :
2.6
URL. , URL
2.6. 75
-
Symfony Documentation, 2.0
index.php?article_id=57 /read/intro-to-symfony.
- , . , URL /blog /news? - ? Symfony, .
Symfony2 URL, - . :
, ;
URL ;
( -);
.
2.6.1
URL ., , URL /blog/my-post /blog/all-about-symfony , . - :
YAML
# app/config/routing.ymlblog_show:
pattern: /blog/{slug}
defaults: { _controller: AcmeBlogBundle:Blog:show }
XML
AcmeBlogBundle:Blog:show
PHP
76 2.
-
Symfony Documentation, 2.0
-
Symfony Documentation, 2.0
2.6.2 ;
, , . URL ( URI) : /contact, /blog/read-me - . HTTP- :
GET /blog/my-blog-post
Symfony2 - URL , . :
1. - Symfony2 ( app.php);
2. Symfony2 (Kernel), ;
3. URL , , ;
4. Symfony2 , - Response.
. 2.2: - , URL , .
2.6.3
Symfony , , . , app/config/routing.yml, ( XML PHP) :
78 2.
-
Symfony Documentation, 2.0
YAML
# app/config/config.ymlframework:
# ...router: { resource: "%kernel.root_dir%/config/routing.yml" }
XML
PHP
2.6. 79
-
Symfony Documentation, 2.0
AcmeDemoBundle:Main:homepage
PHP
AcmeBlogBundle:Blog:show
80 2.
-
Symfony Documentation, 2.0
PHP
AcmeBlogBundle:Blog:index
PHP
2.6. 81
-
Symfony Documentation, 2.0
AcmeBlogBundle:Blog:index
PHP
-
Symfony Documentation, 2.0
{slug}, {page} . , , .
-! , - /blog. , , URL /blog/1! , {page} . - , defaults:
YAML
blog:
pattern: /blog/{page}
defaults: { _controller: AcmeBlogBundle:Blog:index, page: 1 }
XML
AcmeBlogBundle:Blog:index
1
PHP
-
Symfony Documentation, 2.0
/blog {page} = 1/blog/1 {page} = 1/blog/2 {page} = 2
, :
YAML
blog:
pattern: /blog/{page}
defaults: { _controller: AcmeBlogBundle:Blog:index, page: 1 }
blog_show:
pattern: /blog/{slug}
defaults: { _controller: AcmeBlogBundle:Blog:show }
XML
AcmeBlogBundle:Blog:index
1
AcmeBlogBundle:Blog:show
PHP
-
Symfony Documentation, 2.0
$collection->add('blog_show', new Route('/blog/{show}', array(
'_controller' => 'AcmeBlogBundle:Blog:show',
)));
return $collection;
? , - URL /blog/*. Symfony , . , blog_show -. URL /blog/my-blog-post - (blog) {page} my-blog-post.
URL route parameters/blog/2 blog {page} = 2/blog/my-blog-post blog {page} = my-blog-post
. , /blog/{page} URL , {page} . , . :
YAML
blog:
pattern: /blog/{page}
defaults: { _controller: AcmeBlogBundle:Blog:index, page: 1 }
requirements:
page: \d+
XML
AcmeBlogBundle:Blog:index
1
\d+
PHP
-
Symfony Documentation, 2.0
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('blog', new Route('/blog/{page}', array(
'_controller' => 'AcmeBlogBundle:Blog:index',
'page' => 1,
), array(
'page' => '\d+',
)));
return $collection;
\d+ - , , {page} . blog - URL /blog/2 ( 2 ), - URL /blog/my-blog-post ( my-blog-post ).
URL /blog/my-blog-post blog_show.
URL route parameters/blog/2 blog {page} = 2/blog/my-blog-post blog_show {slug} = my-blog-post
, ? blog_show blog, URL /blog/2 - blog_show blog {slug} . .
- , - . , - , URL:
YAML
homepage:
pattern: /{culture}
defaults: { _controller: AcmeDemoBundle:Main:homepage, culture: en }
requirements:
culture: en|fr
XML
-
Symfony Documentation, 2.0
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">
AcmeDemoBundle:Main:homepage
en
en|fr
PHP
-
Symfony Documentation, 2.0
requirements:
_method: GET
contact_process:
pattern: /contact
defaults: { _controller: AcmeDemoBundle:Main:contactProcess }
requirements:
_method: POST
XML
AcmeDemoBundle:Main:contact
GET
AcmeDemoBundle:Main:contactProcess
POST
PHP
-
Symfony Documentation, 2.0
, (/contact), GET-, , , POST-. , , URL .
: _method , - .
, _method - . , GET POST , GET|POST.
, , Symfony. , :
YAML
article_show:
pattern: /articles/{culture}/{year}/{title}.{_format}
defaults: { _controller: AcmeDemoBundle:Article:show, _format: html }
requirements:
culture: en|fr
_format: html|rss
year: \d+
XML
AcmeDemoBundle:Article:show
html
en|fr
html|rss
\d+
2.6. 89
-
Symfony Documentation, 2.0
PHP
-
Symfony Documentation, 2.0
_controller: , , , URL;
_format: (. _format);
_locale: , (. URL);
2.6.4
_controller, , , URL. , , Symfony PHP . , :
::
, _controller AcmeBlogBundle:Blog:show, - :
Bundle Controller Class Method NameAcmeBlogBundle BlogController showAction
:
-
Symfony Documentation, 2.0
: , Symfony . - ( service_name:indexAction) , (. ).
2.6.5
( {slug}) , -:
-
Symfony Documentation, 2.0
2.6.6
, app/config/routing.yml (. ). , . :
YAML
# app/config/routing.ymlacme_hello:
resource: "@AcmeHelloBundle/Resources/config/routing.yml"
XML
PHP
-
Symfony Documentation, 2.0
# src/Acme/HelloBundle/Resources/config/routing.ymlacme_hello:
pattern: /hello/{name}
defaults: { _controller: AcmeHelloBundle:Hello:index }
XML
AcmeHelloBundle:Hello:index
PHP
-
Symfony Documentation, 2.0
XML
PHP
-
Symfony Documentation, 2.0
php app/console router:debug article_show
2.6.8 URL
URL. , - : URL (+ ), - (+ -) URL. :method:`Symfony\\Component\\Routing\\Router::match` :method:`Symfony\\Component\\Routing\\Router::generate` . blog_show, :
-
Symfony Documentation, 2.0
URL
, URL ( /blog). , URL, true generate():
-
Symfony Documentation, 2.0
Twig
Read this blog post.
PHP
-
Symfony Documentation, 2.0
Welcome to Symfony!
-
Symfony Documentation, 2.0
: -: {# #}. PHP- /* comment */.
Twig , -. title :
{{ title | upper }}
Twig (tags) (lters). Twig, .
: Twig : twig.extension.
, Twig , - . , for cycle , div css- odd even:
{% for i in 0..10 %}
{% endfor %}
, Twig-, PHP.
100 2.
http://twig.sensiolabs.org/doc/tags/index.htmlhttp://twig.sensiolabs.org/doc/templates.html#filtershttp://twig.sensiolabs.org/doc/advanced.html -
Symfony Documentation, 2.0
Twig?
Twig PHP . -: Twig , . Twig, . - .Twig , PHP, (Twig- PHP-, ), , ( ), . Twig , - . , if:
{% for user in users %}{{ user.username }}
{% else %}No users found
{% endfor %}
Twig
Twig . Twig- PHP-, . - app/cache/{environment}/twig ( {environment} - , dev prod) . .
debug ( , dev ), Twig - , -. , .
debug ( , prod ), Twig . .
2.7.2 Layout
, (header), (footer), .. Symfony2
2.7. 101
-
Symfony Documentation, 2.0
: . - PHP: - .. layout, -, ( PHP- ). (- PHP- ).
(layout):
Twig
{# app/Resources/views/base.html.twig #}
{% block title %} Test Application{% endblock %}
{% block sidebar %}
Home
Blog
{% endblock %}
{% block body %} {% endblock %}
PHP
-
Symfony Documentation, 2.0
Home
Blog
: Twig, PHP .
HTML- . {% block %} ( title,sidebar body). , . . title, sidebar body .
:
Twig
{# src/Acme/BlogBundle/Resources/views/Blog/index.html.twig #}{% extends '::base.html.twig' %}
{% block title %} My cool blog posts{% endblock %}
{% block body %}{% for entry in blog_entries %}
{{ entry.title }}
{{ entry.body }}
{% endfor %}{% endblock %}
PHP
2.7. 103
-
Symfony Documentation, 2.0
: - ( ::base.html.twig), , app/Resources/views. .
{% extends %}. , , . - , , title body . blog_entries, :
My cool blog posts
Home
Blog
My first post
The body of the first post.
Another post
The body of the second post.
, sidebar, - . {% block %} - .
104 2.
-
Symfony Documentation, 2.0
, . - , , Symfony2 .
, -:
{% extends %} , .
{% block %} , . , , - , . , layout.
, , {% block %} . , (. ).
, - {{ parent() }}. , -, , .
{% block sidebar %}Table of Contents
...
{{ parent() }}{% endblock %}
2.7.3
, :
app/Resources/views/: views , ( layout ), , - (. );
///Resources/views/: Resources/views ( ). .
Symfony2 bundle:controller:template . - , :
2.7. 105
-
Symfony Documentation, 2.0
AcmeBlogBundle:Blog:index.html.twig: . , (:) :
AcmeBlogBundle: (), AcmeBlogBundle( src/Acme/BlogBundle);
Blog: (), , - Blog Resources/views;
index.html.twig: (), - index.html.twig.
AcmeBlogBundle src/Acme/BlogBundle, :src/Acme/BlogBundle/Resources/views/Blog/index.html.twig.
AcmeBlogBundle::layout.html.twig: , - AcmeBlogBundle. , Resources/views/layout.html.twig AcmeBlogBundle.
::base.html.twig: -(layout) . , (::), : app/Resources/views/.
, -, , AcmeBlogBundle, app/Resources/AcmeBlogBundle/views/. .
: - (. ).
bundle:controller:template . , .
AcmeBlogBundle:Blog:index.html.twig - HTML , - Twig;
AcmeBlogBundle:Blog:index.html.php - HTML , - PHP;
AcmeBlogBundle:Blog:index.css.twig - CSS , - Twig.
, Symfony2 Twig PHP (.twig .php) ,
106 2.
-
Symfony Documentation, 2.0
. (.html, .css ..) - , . -, Symfony2 , , HTML (index.html.twig), XML (index.xml.twig) , . .
: - . -
2.7.4
: : - (helper) .
, - . . , , - , .
Symfony2 Twig, - . PHP - , .
Twig ({% block %} & {% extends %}), PHP- ($view['slots']). .
. , -, , , , , .
PHP-, . . , - , , . , :
2.7. 107
-
Symfony Documentation, 2.0
Twig
{# src/Acme/ArticleBundle/Resources/views/Article/articleDetails.html.twig #}{{ article.title }} by {{ article.authorName }}
{{ article.body }}
PHP
by
:
Twig
{# src/Acme/ArticleBundle/Resources/Article/list.html.twig #}{% extends 'AcmeArticleBundle::layout.html.twig' %}
{% block body %}Recent Articles
{% for article in articles %}{% include 'AcmeArticleBundle:Article:articleDetails.html.twig' with {'article': article} %}
{% endfor %}{% endblock %}
PHP
Recent Articles
{% include %}. -
108 2.
-
Symfony Documentation, 2.0
, . articleDetails.html.twig article. list.html.twig with.
: {'article': article} - ( ) Twig. - : {'foo': foo, 'bar': bar}.
, , - . , , . , .
- . -, , :
-
Symfony Documentation, 2.0
, , , , - . - .
- - . , URL , Twig- path ( PHP - router) URL, - . , URL , . - URL.
110 2.
-
Symfony Documentation, 2.0
_welcome, :
YAML
_welcome:
pattern: /
defaults: { _controller: AcmeDemoBundle:Welcome:index }
XML
AcmeDemoBundle:Welcome:index
PHP
-
Symfony Documentation, 2.0
-
Symfony Documentation, 2.0
PHP
-
Symfony Documentation, 2.0
{% block stylesheets %}
{% endblock %}
{# ... #}
{% block javascripts %}
{% endblock %}
! , ? , contact.css . contact :
{# src/Acme/DemoBundle/Resources/views/Contact/contact.html.twig #}{# extends '::base.html.twig' #}
{% block stylesheets %}{{ parent() }}
{% endblock %}
{# ... #}
stylesheets . , , , parent() , .
, Resources/public . php app/consoleassets:install target [--symlink], ( - ) (target web.
, main.css, contact.css
114 2.
-
Symfony Documentation, 2.0
2.7.6
Symfony2 (Engine). - , ., , -:
-
Symfony Documentation, 2.0
: Twig - ( ).
2.7.7
Symfony2 , - (. Symfony2Bundles.org) . , - .
, AcmeBlogBundle. , -, , - list , . Blog AcmeBlogBundle, :
-
Symfony Documentation, 2.0
, , Symfony2 app/Resources/{BUNDLE_NAME}/views/. , Resources/views . , - app/Resources.
Symfony2 , . , TwigBundle - , , - Resources/views/Exception TwigBundle app/Resources/TwigBundle/views/Exception.
2.7.8
- . - , -:
app/Resources/views/base.html.twig, - ( ). - ::base.html.twig;
. AcmeBlogBundle - AcmeBlogBundle::layout.html.twig, ;
{# src/Acme/BlogBundle/Resources/views/layout.html.twig #}{% extends '::base.html.twig' %}
{% block body %}Blog Application
{% block content %} {% endblock %}{% endblock %}
- (). , index - AcmeBlogBundle:Blog:index.html.twig :
{# src/Acme/BlogBundle/Resources/views/Blog/index.html.twig #}{% extends 'AcmeBlogBundle::layout.html.twig' %}
{% block content %}{% for entry in blog_entries %}
2.7. 117
-
Symfony Documentation, 2.0
{{ entry.title }}
{{ entry.body }}
{% endfor %}{% endblock %}
, AcmeBlogBundle::layout.html.twig, , , - (::base.html.twig). .
- - ({% extends '::base.html.twig' %}). - , .
2.7.9
HTML , , HTML- . - HTML Cross Site Scripting (XSS) . :
Twig
Hello {{ name }}
PHP
Hello
, :
alert('hello!')
, :
Hello alert('hello!')
() JavaScript alert.
, , .
(output escaping). , :
118 2.
http://en.wikipedia.org/wiki/Cross-site_scripting -
Symfony Documentation, 2.0
Hello alert('helloe')
Twig PHP . - Twig, . PHP - .
Twig
Twig, . -, . , , HTML.
, , HTML-, - . , - , HTML-. Twig . raw: {{ article.body | raw }}.
-. Twig: Output Escaping.
PHP
PHP . , - - . escape():
Hello
, escape() , HTML - ( HTML). . , - JavaScript js:
var myMsg = 'Hello ';
2.7.10
- . - HTML , JavaScript, CSS, XML .
2.7. 119
http://twig.sensiolabs.org -
Symfony Documentation, 2.0
, . - XML , :
XML template name: AcmeArticleBundle:Article:index.xml.twig
XML template lename: index.xml.twig
- - .
. :
-
Symfony Documentation, 2.0
. , , - - , . Response, , :
-
Symfony Documentation, 2.0
2.8.1 : Product
Doctrine - . , Product (), .
AcmeStoreBundle:
php app/console generate:bundle --namespace=Acme/StoreBundle
, - . app/config/parameters.yml:
#app/config/parameters.ymlparameters:
database_driver: pdo_mysql
database_host: localhost
database_name: test_project
database_user: root
database_password: password
: parameters.yml . , Doctrine:
doctrine:
dbal:
driver: %database_driver%
host: %database_host%
dbname: %database_name%
user: %database_user%
password: %database_password%
, - . - ( ) -, Apache. /cookbook/configuration/external_parameters.
122 2.
-
Symfony Documentation, 2.0
, Doctrine , :
php app/console doctrine:database:create
, , . - Doctrine , Product . Entity () AcmeStoreBundle:
// src/Acme/StoreBundle/Entity/Product.phpnamespace Acme\StoreBundle\Entity;
class Product
{
protected $name;
protected $price;
protected $description;
}
- , , - . - PHP.
: , Doctrine, -:
php app/console doctrine:generate:entity --entity="AcmeStoreBundle:Product" --fields="name:string(255) price:float description:text"
Doctrine , . ,Doctrine . PHP PHP :
2.8. Doctrine () 123
-
Symfony Documentation, 2.0
Doctrine , -, Product . , YAML, XML Product :
: Bundle ., YAML - - PHP.
Annotations
// src/Acme/StoreBundle/Entity/Product.php
namespace Acme\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="product")
*/
class Product
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", length=100)
*/
protected $name;
124 2.
-
Symfony Documentation, 2.0
/**
* @ORM\Column(type="decimal", scale=2)
*/
protected $price;
/**
* @ORM\Column(type="text")
*/
protected $description;
}
YAML
# src/Acme/StoreBundle/Resources/config/doctrine/Product.orm.ymlAcme\StoreBundle\Entity\Product:
type: entity
table: product
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
name:
type: string
length: 100
price:
type: decimal
scale: 2
description:
type: text
XML
2.8. Doctrine () 125
-
Symfony Documentation, 2.0
: , -, -.
Doctrine , - . - Doctrine.
.:
Doctrine- Basic Mapping Documentation . , - , ORM\ (, ORM\Column(..)), - Doctrine. use Doctrine\ORM\Mapping as ORM;, ORM .
: - SQL ( group user). , Group, , , group, SQL . - SQL .
: (-, Doxygen), , @IgnoreAnnotation, Symfony .
, @fn , :
/*** @IgnoreAnnotation("fn")**/class Product
, Doctrine Product , . Product PHP , (, getName(), setName()) - (. . protected). , Doctrine :
126 2.
http://www.doctrine-project.org/docs/orm/2.0/en/reference/basic-mapping.htmlhttp://www.doctrine-project.org/docs/orm/2.0/en/reference/basic-mapping.html#quoting-reserved-wordshttp://www.doctrine-project.org/docs/orm/2.0/en/reference/basic-mapping.html#quoting-reserved-words -
Symfony Documentation, 2.0
php app/console doctrine:generate:entities Acme/StoreBundle/Entity/Product
Product. - : , (. . ).
: doctrine:generate:entities Product.php Product.php~. , Cannot redeclare class. .
(, PHP - Doctrine) :
php app/console doctrine:generate:entities AcmeStoreBundle
php app/console doctrine:generate:entities Acme
: Doctrine protected private, . - PHP.
/
Product , Doctrine . , product . , Doctrine , . , :
php app/console doctrine:schema:update --force
: . ( ) , , SQL , , . , Product , alter table, product.
, - SQL , .
2.8. Doctrine () 127
-
Symfony Documentation, 2.0
product , - .
, Product product, . . DefaultController :
1 // src/Acme/StoreBundle/Controller/DefaultController.php2 use Acme\StoreBundle\Entity\Product;
3 use Symfony\Component\HttpFoundation\Response;
4 // ...5
6 public function createAction()
7 {
8 $product = new Product();
9 $product->setName('A Foo Bar');
10 $product->setPrice('19.99');
11 $product->setDescription('Lorem ipsum dolor');
12
13 $em = $this->getDoctrine()->getEntityManager();
14 $em->persist($product);
15 $em->flush();
16
17 return new Response('Created product id '.$product->getId());
18 }
: , , - , .
:
8-11 , $product - PHP ;
13 Doctrine- entity manager, - ;
14 persist() Doctrine $product. ().
15 flush(), Doctrine , , , .
128 2.
-
Symfony Documentation, 2.0
$product , entity manager INSERT product.
: , . . Doctrine , - flush(), . , 100 Product flush(), Doctrine - . Unit of Work .
. Doctrine UPDATE .
: Doctrine , - (. . xture data). /bundles/DoctrineFixturesBundle/index.
. , - , Product, id:
public function showAction($id)
{
$product = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Product')
->find($id);
if (!$product) {
throw $this->createNotFoundException('No product found for id '.$id);
}
// -, $product }
, . PHP , . - - - :
$repository = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Product');
2.8. Doctrine () 129
-
Symfony Documentation, 2.0
: AcmeStoreBundle:Product - , - Doctrine (,Acme\StoreBundle\Entity\Product). Entity .
, :
// ( "id")$product = $repository->find($id);
// , $product = $repository->findOneById($id);
$product = $repository->findOneByName('foo');
// ** $products = $repository->findAll();
// , $products = $repository->findByPrice(19.99);
: , , - .
findBy findOneBy , :
// , $product = $repository->findOneBy(array('name' => 'foo', 'price' => 19.99));
// , $product = $repository->findBy(
array('name' => 'foo'),
array('price' => 'ASC')
);
: , - web debug.
130 2.
-
Symfony Documentation, 2.0
, , , .
Doctrine, . , , id :
public function updateAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$product = $em->getRepository('AcmeStoreBundle:Product')->find($id);
if (!$product) {
throw $this->createNotFoundException('No product found for id '.$id);
}
$product->setName('New product name!');
$em->flush();
return $this->redirect($this->generateUrl('homepage'));
}
:
1. Doctrine;
2. ;
3. flush() entity manager
, $em->persist($product) . , Doctrine $product. , . . $product Doctrine, .
2.8. Doctrine () 131
-
Symfony Documentation, 2.0
, remove() entity manager:
$em->remove($product);
$em->flush();
, remove() Doctrine , . , DELETE , flush() .
2.8.2
- - :
$repository->find($id);
$repository->findOneByName('Foo');
, Doctrine , DoctrineQuery Language (DQL). DQL SQL , - - (,Product) (, product).
Doctrine : Doctrine - Doctrine- Query Builder.
DQL
, , 19.99 . :
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery(
'SELECT p FROM AcmeStoreBundle:Product p WHERE p.price > :price ORDER BY p.price ASC'
)->setParameter('price', '19.99');
$products = $query->getResult();
SQL, DQL . , , . , AcmeStoreBundle:Product p.
132 2.
-
Symfony Documentation, 2.0
getResult() . getSingleResult():
$product = $query->getSingleResult();
: getSingleResult() - Doctrine\ORM\NoResultException Doctrine\ORM\NonUniqueResultException . , try-catch , ( -, ):
$query = $em->createQuery('SELECT ....')
->setMaxResults(1);
try {
$product = $query->getSingleResult();
} catch (\Doctrine\Orm\NoResultException $e) {
$product = null;
}
// ...
DQL , - ( ), . . - Doctrine Doctrine Query Language.
setParameter(). Doctrine, placeholders, - :
... WHERE p.price > :price ...
price placeholder setParameter():
->setParameter('price', '19.99')
SQL -. , setParameters():
->setParameters(array(
'price' => '19.99',
'name' => 'Foo',
))
2.8. Doctrine () 133
http://www.doctrine-project.org/docs/orm/2.0/en/reference/dql-doctrine-query-language.html -
Symfony Documentation, 2.0
Doctrine's Query Builder ( Doctrine)
, DoctrineQueryBuilder , - . IDE, - - . -:
$repository = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Product');
$query = $repository->createQueryBuilder('p')
->where('p.price > :price')
->setParameter('price', '19.99')
->orderBy('p.price', 'ASC')
->getQuery();
$products = $query->getResult();
QueryBuilder . getQuery(), Query, - , .
Doctrine's Query Builder, - Query Builder.
Custom Repository Classes
. , , custom repository class .
.
Annotations
// src/Acme/StoreBundle/Entity/Product.php
namespace Acme\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="Acme\StoreBundle\Repository\ProductRepository")
*/
class Product
{
134 2.
http://www.doctrine-project.org/docs/orm/2.0/en/reference/query-builder.html -
Symfony Documentation, 2.0
//...
}
YAML
# src/Acme/StoreBundle/Resources/config/doctrine/Product.orm.ymlAcme\StoreBundle\Entity\Product:
type: entity
repositoryClass: Acme\StoreBundle\Repository\ProductRepository
# ...
XML
Doctrine , getter setter :
php app/console doctrine:generate:entities Acme
- findAllOrderedByName() - - . Product, .
// src/Acme/StoreBundle/Repository/ProductRepository.phpnamespace Acme\StoreBundle\Repository;
use Doctrine\ORM\EntityRepository;
class ProductRepository extends EntityRepository
{
public function findAllOrderedByName()
{
return $this->getEntityManager()
->createQuery('SELECT p FROM AcmeStoreBundle:Product p ORDER BY p.name ASC')
->getResult();
}
}
: $this->getEntityManager() -
2.8. Doctrine () 135
-
Symfony Documentation, 2.0
.
:
$em = $this->getDoctrine()->getEntityManager();
$products = $em->getRepository('AcmeStoreBundle:Product')
->findAllOrderedByName();
: custom repository class, find() findAll().
2.8.3 /
. , Category Product. Category. - Doctrine, Doctrine .
php app/console doctrine:generate:entity --entity="AcmeStoreBundle:Category" --fields="name:string(255)"
Category id, name getter setter.
Category Product, products Category:
// src/Acme/StoreBundle/Entity/Category.php// ...use Doctrine\Common\Collections\ArrayCollection;
class Category
{
// ...
/*** @ORM\OneToMany(targetEntity="Product", mappedBy="category")*/protected $products;
136 2.
-
Symfony Documentation, 2.0
public function __construct()
{
$this->products = new ArrayCollection();
}
}
-, . . Category Product, - products Product. , thisisn't done because Doctrine needs it, but instead because it makes sense in the applicationfor each Category to hold an array of Product objects.
: __construct() , Doctrine $products ArrayCollection. , . - , . .
, . . Product Category, $category Product:
// src/Acme/StoreBundle/Entity/Product.php// ...
class Product
{
// ...
/*** @ORM\ManyToOne(targetEntity="Category", inversedBy="products")* @ORM\JoinColumn(name="category_id", referencedColumnName="id")*/protected $category;
}
, Category Product, - Doctrine getter setter:
php app/console doctrine:generate:entities Acme
Doctrine . - Category Productwith a natural one-to-many relationship. Category holds Product Product hold Category. - - , . , , .
$category Product. - doctrine Category
2.8. Doctrine () 137
-
Symfony Documentation, 2.0
id category_id, product. , Category $category,, , Doctrine , id category_id product.
$products Category - Doctrine Product.category .
, Doctrine category product.category_id, :
php app/console doctrine:schema:update --force
138 2.
-
Symfony Documentation, 2.0
: . Doctrine.
. , :
// ...use Acme\StoreBundle\Entity\Category;
use Acme\StoreBundle\Entity\Product;
use Symfony\Component\HttpFoundation\Response;
// ...
class DefaultController extends Controller
{
public function createProductAction()
{
$category = new Category();
$category->setName('Main Products');
$product = new Product();
$product->setName('Foo');
$product->setPrice(19.99);
// $product->setCategory($category);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($category);
$em->persist($product);
$em->flush();
return new Response(
'Created product id: '.$product->getId().' and category id: '.$category->getId()
);
}
}
, category product. product.category_id id, . Doctrine .
2.8. Doctrine () 139
-
Symfony Documentation, 2.0
, - . $product, Category:
public function showAction($id)
{
$product = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Product')
->find($id);
$categoryName = $product->getCategory()->getName();
// ...}
, Product id . (hydrate) $product . , $product->getCategory()->getName(),Doctrine , Category, - Product. $category .
, , , , (. . ).
:
140 2.
-
Symfony Documentation, 2.0
public function showProductAction($id)
{
$category = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Category')
->find($id);
$products = $category->getProducts();
// ...}
: Category, Doctrine Product, - (. . ->getProducts()). $products Product, Category category_id.
proxy
, , , Doctrine - proxy . , - :
$product = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Product')
->find($id);
$category = $product->getCategory();
// prints "Proxies\AcmeStoreBundleEntityCategoryProxy"echo get_class($category);
proxy Category, . , proxy , Doctrine Category (. . $category->getName()).Proxy Doctrine cache. , , $category proxy , . ( join), Doctrine Category, . . .
2.8. Doctrine () 141
-
Symfony Documentation, 2.0
- (, Category) (, Product).
: , , -, web debug.
, , , join . ProductRepository:
// src/Acme/StoreBundle/Repository/ProductRepository.php
public function findOneByIdJoinedToCategory($id)
{
$query = $this->getEntityManager()
->createQuery('
SELECT p, c FROM AcmeStoreBundle:Product p
JOIN p.category c
WHERE p.id = :id'
)->setParameter('id', $id);
try {
return $query->getSingleResult();
} catch (\Doctrine\ORM\NoResultException $e) {
return null;
}
}
Product Category :
public function showAction($id)
{
$product = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Product')
->findOneByIdJoinedToCategory($id);
$category = $product->getCategory();
// ...}
142 2.
-
Symfony Documentation, 2.0
- --. (., --, --), Doctrine.
: , - ORM\ (., ORM\OneToMany), Doctrine. use Doctrine\ORM\Mapping as ORM;, ORM.
2.8.4
Doctrine , , , . Doctrine, see the Doctrine section ofthe reference manual.
2.8.5 Lifecycle Callbacks
- , . lifecyclecallbacks, . . , - (., , , . .).
, lifecyclecallbacks. YAML XML:
/**
* @ORM\Entity()
* @ORM\HasLifecycleCallbacks()
*/
class Product
{
// ...
}
Doctrine . , created (. . ):
Annotations
2.8. Doctrine () 143
http://www.doctrine-project.org/docs/orm/2.0/en/reference/association-mapping.htmlhttp://www.doctrine-project.org/docs/orm/2.0/en/reference/association-mapping.html -
Symfony Documentation, 2.0
/**
* @ORM\prePersist
*/
public function setCreatedValue()
{
$this->created = new \DateTime();
}
YAML
# src/Acme/StoreBundle/Resources/config/doctrine/Product.orm.ymlAcme\StoreBundle\Entity\Product:
type: entity
# ...lifecycleCallbacks:
prePersist: [ setCreatedValue ]
XML
: created ( ).
, Doctrine created .
, :
preRemove
postRemove
prePersist
postPersist
preUpdate
144 2.
-
Symfony Documentation, 2.0
postUpdate
postLoad
loadClassMetadata
, , Lifecycle Events
Lifecycle Callbacks Event Listeners
setCreatedValue() . lifecylce callbacks : lifecycle callbacks , (., created/updated, - slug). - email- event listener subscriber . /cookbook/doctrine/event_listeners_subscribers.
2.8.6 Doctrine: Timestampable, Sluggable -
Doctrine , , . : Sluggable, Timestampable, Loggable, Translatable Tree.
Doctrine.
2.8.7 Doctrine
Doctrine . - PHP . Doctrine :
string ( )
text ( )
integer
2.8. Doctrine () 145
http://www.doctrine-project.org/docs/orm/2.0/en/reference/events.html#lifecycle-events -
Symfony Documentation, 2.0
smallint
bigint
decimal
float
( DateTime PHP )
date
time
datetime
boolean
object ( CLOB)
array ( CLOB)
.
, . -: type ( string), name, length, unique nullable. :
/**
* 255, null
* ( "type", "length" *nullable*)
*
* @ORM\Column()
*/
protected $name;
/**
* 150, "email_address"
* .
*
* @ORM\Column(name="email_address", unique="true", length="150")
*/
protected $email;
: , . - Doctrine's Property Mappingdocumentation
146 2.
http://php.net/manual/en/class.datetime.phphttp://www.doctrine-project.org/docs/orm/2.0/en/reference/basic-mapping.html#doctrine-mapping-typeshttp://www.doctrine-project.org/docs/orm/2.0/en/reference/basic-mapping.html#property-mappinghttp://www.doctrine-project.org/docs/orm/2.0/en/reference/basic-mapping.html#property-mapping -
Symfony Documentation, 2.0
2.8.8
Doctrine2 ORM - doctrine. :
php app/console
doctrine:. ( Symfony) help. , doctrine:database:create, :
php app/console help doctrine:database:create
:
doctrine:ensure-production-settings - , - . - prod:
php app/console doctrine:ensure-production-settings --env=prod
doctrine:mapping:import - Doctrine . - /cookbook/doctrine/reverse_engineering.
doctrine:mapping:info - , Doctrine, - .
doctrine:query:dql doctrine:query:sql - DQL SQL .
: xtures , DoctrineFixturesBundle. , /bundles/DoctrineFixturesBundle/index .
2.8.9
Doctrine, - . , Doctrine PHP .
2.8. Doctrine () 147
-
Symfony Documentation, 2.0
Doctrine , , - , - -.
Doctrine Doctrine , :
/bundles/DoctrineFixturesBundle/index
/cookbook/doctrine/common_extensions
2.9
, . , , (unit) .
2.9.1 PHPUnit
Symfony2 - PHPUnit- . PHPUnit, .
: Symfony2 PHPUnit 3.5.11 .
- - PHP, Tests/ . , :
# $ phpunit -c app/
-c PHPUnit app/. PHPUnit, app/phpunit.xml.dist.
: --coverage-html.
148 2.
http://www.phpunit.de/manual/3.5/en/ -
Symfony Documentation, 2.0
2.9.2
- PHP . , - .
Symfony2 - PHPUnit. , , Calculator Utility/ :
-
Symfony Documentation, 2.0
, - bootstrap.php.cache ( phpunit.xml.dist).
:
# run all tests in the Utility directory$ phpunit -c app src/Acme/DemoBundle/Tests/Utility/
# run tests for the Calculator class$ phpunit -c app src/Acme/DemoBundle/Tests/Utility/CalculatorTest.php
# Bundle$ phpunit -c app src/Acme/DemoBundle/
2.9.3
( ). , - PHPUnit , :
;
;
;
;
.
- PHP , , , - Tests/Controller. , DemoController, , - WebTestCase.
, Symfony2 Standard Edition DemoController (DemoControllerTest), :
-
Symfony Documentation, 2.0
public function testIndex()
{
$client = static::createClient();
$crawler = $client->request('GET', '/demo/hello/Fabien');
$this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
}
}
: , WebTestCase - . , . , , - phpunit.xml.dist KERNEL_DIR :
createClient() , , :
$crawler = $client->request('GET', '/demo/hello/Fabien');
request() (. request) Symfony\Component\DomCrawler\Crawler, Response, .
: Crawler , Response XML HTML . Response $client->getResponse()->getContent().
, Crawler XPath CSS, Client . , Greet, :
$link = $crawler->filter('a:contains("Greet")')->eq(1)->link();
$crawler = $client->click($link);
2.9. 151
-
Symfony Documentation, 2.0
: , - , :
-
Symfony Documentation, 2.0
request():
request():
-
Symfony Documentation, 2.0
$this->assertTrue($client->getResponse()->isSuccessful());
// - 404$this->assertTrue($client->getResponse()->isNotFound());
// - 200$this->assertEquals(200, $client->getResponse()->getStatusCode());
// - /demo/contact$this->assertTrue($client->getResponse()->isRedirect('/demo/contact'));
// , - URL$this->assertTrue($client->getResponse()->isRedirect());
2.9.4
HTTP ( ) Symfony2 :
$crawler = $client->request('GET', '/hello/Fabien');
request() HTTP URL Crawler.
Crawler DOM- Response. - :
-
Symfony Documentation, 2.0
// use Symfony\Component\HttpFoundation\File\UploadedFile;
$photo = new UploadedFile(
'/path/to/photo.jpg',
'photo.jpg',
'image/jpeg',
123
);
// $photo = array(
'tmp_name' => '/path/to/photo.jpg',
'name' => 'photo.jpg',
'type' => 'image/jpeg',
'size' => 123,
'error' => UPLOAD_ERR_OK
);
$client->request(
'POST',
'/submit',
array('name' => 'Fabien'),
array('photo' => $photo)
);
// DELETE , HTTP $client->request(
'DELETE',
'/post/12',
array(),
array(),
array('PHP_AUTH_USER' => 'username', 'PHP_AUTH_PW' => 'pa$$word')
);
, , - PHP :
$client->insulate();
, :
-
Symfony Documentation, 2.0
$client->reload();
// .$client->restart();
, :
-
Symfony Documentation, 2.0
Symfony . , , SQL , .
:
$profile = $client->getProfile();
: - .
, . , followRedirects():
$client->followRedirects(false);
, followRedirect():
$crawler = $client->followRedirect();
2.9.5 Crawler
Crawler . HTML , , .
jQuery, Crawler DOM HTML/XML., input[type=submit], - :
-
Symfony Documentation, 2.0
:
filter('h1.title') , CSS filterXpath('h1') , XPatheq(1) first() last() siblings() ()nextAll() previousAll() parents() children() reduce($lambda) , false
Crawler, :
-
Symfony Documentation, 2.0
// lambda $data = $crawler->each(function ($node, $i)
{
return $node->attr('href');
});
, selectLink() :
$crawler->selectLink('Click here');
, , , , alt.
click() Link, link():
$link = $crawler->link();
$client->click($link);
: links() Link .
, selectButton():
$crawler->selectButton('submit');
, , . . ; API , .
selectButton() button input submit; - :
value;
id alt ;
id name button.
, , form() - Form, :
2.9. 159
-
Symfony Documentation, 2.0
$form = $buttonCrawlerNode->form();
form() , - :
$form = $buttonCrawlerNode->form(array(
'name' => 'Fabien',
'my_form[subject]' => 'Symfony rocks!',
));
HTTP , - :
$form = $crawler->form(array(), 'DELETE');
Form:
$client->submit($form);
submit():
$client->submit($form, array(
'name' => 'Fabien',
'my_form[subject]' => 'Symfony rocks!',
));
, Form - :
// $form['name'] = 'Fabien';
$form['my_form[subject]'] = 'Symfony rocks!';
API :
// option radio$form['country']->select('France');
// checkbox$form['like_symfony']->tick();
// $form['photo']->upload('/path/to/lucas.jpg');
: , , getValues() Form. , - getFiles(). getPhpValues() getPhpFiles() -
160 2.
-
Symfony Documentation, 2.0
, PHP ( - , my_form[subject] - PHP ).
2.9.6
PHPUnit
PHPUnit, - phpunit.xml.dist. phpunit.xml - .
: phpunit.xml.dist phpunit.xml.
, phpunit ( src/*/Bundle/Tests src/*/Bundle/*Bundle/Tests), ., :
../src/*/*Bundle/Tests
../src/Acme/Bundle/*Bundle/Tests
, , :
../src
../src/*/*Bundle/Resources
../src/*/*Bundle/Tests
../src/Acme/Bundle/*Bundle/Resources
../src/Acme/Bundle/*Bundle/Tests
2.9. 161
-
Symfony Documentation, 2.0
2.9.7
HTTP
2.10
- web-. , (). , , web-.
Symfony2 Validator , . JSR303 Bean Validation specication. ?! Java - PHP? , . , PHP.
2.10.1
- . ,, PHP- - :
-
Symfony Documentation, 2.0
YAML
# src/Acme/BlogBundle/Resources/config/validation.ymlAcme\BlogBundle\Entity\Author:
properties:
name:
- NotBlank: ~
Annotations
// src/Acme/BlogBundle/Entity/Author.php
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
/**
* @Assert\NotBlank()
*/
public $name;
}
XML
PHP
-
Symfony Documentation, 2.0
{
$metadata->addPropertyConstraint('name', new NotBlank());
}
}
: (protected) (private) get- (. validator-constraint-targets).
validator
, Author, validate validator(class Symfony\Component\Validator\Validator). validator -: (.. ), , , . , . -:
-
Symfony Documentation, 2.0
: - validator . . : .
.
: ( constraint violation), - Symfony\Component\Validator\ConstraintViolation
2.10. 165
-
Symfony Documentation, 2.0
validator . , , validator . Symfony , . (constraint violations) - FieldError, . :
-
Symfony Documentation, 2.0
):
YAML
# app/config/config.ymlframework:
validation: { enable_annotations: true }
XML
PHP
-
Symfony Documentation, 2.0
Blank
NotNull
Null
True
False
Type
Email
MinLength
MaxLength
Url
Regex
Ip
Max
Min
Date
DateTime
Time
Choice
Collection
UniqueEntity
Language
168 2.
-
Symfony Documentation, 2.0
Locale
Country
File
Image
Callback
All
UserPassword
Valid
. /cookbook/validation/custom_constraint .
, NotBlank, , , - Choice, . , Author gender, - male female:
YAML
# src/Acme/BlogBundle/Resources/config/validation.ymlAcme\BlogBundle\Entity\Author:
properties:
gender:
- Choice: { choices: [male, female], message: Choose a valid gender. }
Annotations
// src/Acme/BlogBundle/Entity/Author.php
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
/**
* @Assert\Choice(
* choices = { "male", "female" },
* message = "Choose a valid gender."
2.10. 169
-
Symfony Documentation, 2.0
* )
*/
public $gender;
}
XML
male
female
Choose a valid gender.
PHP
-
Symfony Documentation, 2.0
Choice, (choices).
YAML
# src/Acme/BlogBundle/Resources/config/validation.ymlAcme\BlogBundle\Entity\Author:
properties:
gender:
- Choice: [male, female]
Annotations
// src/Acme/BlogBundle/Entity/Author.php
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
/**
* @Assert\Choice({"male", "female"})
*/
protected $gender;
}
XML
male
female
PHP
-
Symfony Documentation, 2.0
{
protected $gender;
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('gender', new Choice(array('male', 'female')));
}
}
.
, , API - ( ).
2.10.4
(, name) - ( , , getFullName). , - .
- . Symfony2 , . $firstName Author, .
YAML
# src/Acme/BlogBundle/Resources/config/validation.ymlAcme\BlogBundle\Entity\Author:
properties:
firstName:
- NotBlank: ~
- MinLength: 3
Annotations
// Acme/BlogBundle/Entity/Author.php
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
172 2.
-
Symfony Documentation, 2.0
/**
* @Assert\NotBlank()
* @Assert\MinLength(3)
*/
private $firstName;
}
XML
3
PHP
-
Symfony Documentation, 2.0
, true:
YAML
# src/Acme/BlogBundle/Resources/config/validation.ymlAcme\BlogBundle\Entity\Author:
getters:
passwordLegal:
- "True": { message: "The password cannot match your first name" }
Annotations
// src/Acme/BlogBundle/Entity/Author.php
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
/**
* @Assert\True(message = "The password cannot match your first name")
*/
public function isPasswordLegal()
{
// return true or false
}
}
XML
The password cannot match your first name
PHP
-
Symfony Documentation, 2.0
'message' => 'The password cannot match your first name',
)));
}
}
isPasswordLegal() :
public function isPasswordLegal()
{
return ($this->firstName != $this->password);
}
: , - (get is). - ( , , ) .
. Callback - , . , , .
2.10.5
, . , -, , . , .
, User, - :
YAML
# src/Acme/BlogBundle/Resources/config/validation.ymlAcme\BlogBundle\Entity\User:
properties:
email:
- Email: { groups: [registration] }
password:
2.10. 175
-
Symfony Documentation, 2.0
- NotBlank: { groups: [registration] }
- MinLength: { limit: 7, groups: [registration] }
city:
- MinLength: 2
Annotations
// src/Acme/BlogBundle/Entity/User.php
namespace Acme\BlogBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
class User implements UserInterface
{
/**
* @Assert\Email(groups={"registration"})
*/
private $email;
/**
* @Assert\NotBlank(groups={"registration"})
* @Assert\MinLength(limit=7, groups={"registration"})
*/
private $password;
/**
* @Assert\MinLength(2)
*/
private $city;
}
XML
registration
registration
176 2.
-
Symfony Documentation, 2.0
7
registration
7
PHP
-
Symfony Documentation, 2.0
, , - validate():
$errors = $validator->validate($author, array('registration'));
, , . , .
2.10.6
. , - , , - email-. . - :
-
Symfony Documentation, 2.0
, , . - - Symfony\Component\Validator\ConstraintViolation, , , getMessage.
2.10.7
Symfony2 - , , . - -, , . - , , .
2.10.8 :
/cookbook/validation/custom_constraint
2.11
- web-. Symfony2 , - . , , .
: - , - Symfony2. Symfony2 Form Component .
2.11.1
, - ToDo, . , . , , Task, :
-
Symfony Documentation, 2.0
class Task
{
protected $task;
protected $dueDate;
public function getTask()
{
return $this->task;
}
public function setTask($task)
{
$this->task = $task;
}
public function getDueDate()
{
return $this->dueDate;
}
public function setDueDate(\DateTime $dueDate = null)
{
$this->dueDate = $dueDate;
}
}
: , , AcmeTaskBundle, ( ):
php app/console generate:bundle --namespace=Acme/TaskBundle
PHP- Symfony - . PHP-, - (.. ). , Task ( HTML-), .
, Task, HTML-. Symfony2 . , :
180 2.
-
Symfony Documentation, 2.0
-
Symfony Documentation, 2.0
, , . , form view ( - $form->createView() ) - :
Twig
{# src/Acme/TaskBundle/Resources/views/Default/new.html.twig #}
{{ form_widget(form) }}
PHP
>
: , task_new, AcmeTaskBundle:Default:new, .
! form_widget(form), , ( ). , ( ). , , , . , .
182 2.
-
Symfony Documentation, 2.0
, , task, task $task (Write a blog post). - : , HTML .
: , - (protected) task getTask() setTask() Task. (public), , . - is* ( isPublished()) getPublished().
, , . , . :
-
Symfony Documentation, 2.0
, task dueDate $task. bindRequest().
: bindRequ