If you can't read please download the document
Upload
necio-de-lima-veras
View
4.321
Download
9
Embed Size (px)
DESCRIPTION
Aula introdutória sobre o framework Symfony2.
Citation preview
2. Parte I: Conhecendo...
3. ...o que o Symfony2 4. ...se um framework MVC 5. ...os componentes 6. ...as inovaes 7. ...por onde comear 8. Sobre o criador ... Fabien Potencier @fabpotParis, France Sensio CEO (sensiolabs.com) and Symfony lead developer (symfony.com)http://fabien.potencier.org WorkCEO at Sensio AboutFabien discovered the Web in 1994, at a time when connecting to the Internet was still associated with the harmful strident sounds of a modem. Being a developer by passion, he immediately started to build websites with Perl. But with the release of PHP 5, he decided to switch focus to PHP, and created the symfony framework project in 2004 to help his company leverage the power of PHP for its customers. Fabien is a serial-entrepreneur, and among other companies, he created Sensio, a services and consulting company specialized in web technologies and Internet marketing, in 1998. Fabien is also the creator of several other Open-Source projects, a writer, a blogger, a speaker at internatio 9. Fabien Potencier
11. The state of YAML in PHP 12. Symfony Service Container: Using XML or YAML to describe Services
13. Fabien Potencier
14. http://symfony.com/blog/ 15. Compartilha slides produzidos/apresentados em eventos 16. http://www.slideshare.net/fabpot 17. Publica ainda na rede social dos codificadores vrios repositrios pblicos de projetos 18. https://github.com/fabpot 19. Oficializao do Symfony2... After 12 preview releases, 5 beta versions, and 6 release candidates, I'm very orgulhoso to announce the immediate availability of Symfony 2.0, final version. Since the first preview release, published 18 months ago during the Symfony Live conference, the Symfony community has done an amazing work. The Symfony2 code quality would not have been the same without their outstanding work. Thank you! Symfony 2.0 (http://symfony.com/blog/symfony-2-0)by Fabien Potencier July 28, 2011 20. A comunidade...
21. Since March 2011, more than 100 new contributors have joined the Symfony2 team (250 vs 150); and more than 250 new bundles have been created on Github (440 vs 170) Symfony 2.0 (http://symfony.com/blog/symfony-2-0)by Fabien Potencier July 28, 2011 22. What is Symfony2?
23. Then, based on these components, Symfony2 is also a full-stack web framework 24. Dependendo do seu projeto e de suas necessidades, voc pode escolher alguns dos componentes do Symfony2 e iniciar o projeto com eles, ou voc pode usar tudo do framework e se beneficiar com a integrao que ele proporciona Fabien Potencier publicado em seu blog pessoal (25/10/11) 25. Is Symfony2 an MVC framework?
Fabien Potencier publicado em seu blog pessoal (25/10/11) 26. Is Symfony2 an MVC framework?
27. Symfony2 is a great framework for bigger projects where tens of developers are involved and where the business logic is more complex. And the Symfony2 components are for people who don't want to use a framework, or for other Open-Source projects thatdon't want to reinvent the wheel Fabien Potencier publicado em seu blog pessoal (25/10/11) 28. The Symfony2 Component Fabien Potencier publicado em seu blog pessoal (25/10/11)
29. EventDispatcher 30. HttpFoundation 31. DomCrawler 32. ClassLoader 33. CssSelector 34. HttpKernel 35. BrowserKit 36. Templating 37. Translation 38. Serializer
39. Security 40. Routing 41. Console 42. Process 43. Config 44. Finder 45. Locale 46. Yaml 47. Form 48. Symfony2: Inovaes nicas no mundo PHP
49. Distributions : A distribution is a pre-configured Symfony2 project with a selection of bundles and sensible defaults. The Symfony Standard Edition also comes with a Web configurator. That makes the installation and configuration of a new Symfony2 project fast and insanely easy 50. Everything is a Bundle in Symfony2 : A bundle is a directory containing a set of files (PHP files, stylesheets, JavaScripts, images, ...) that implement a single feature (a blog, a forum, etc). That changes everything. Share your bundles between your projects or publish them in the wild 51. Symfony2 is Fast : the raw performance of the framework is great, but there is more 52. [...] Fabien Potencier publicado em http://symfony.com/blog/symfony-2-0 53. Symfony2:[novas]caractersticas
54. O console est dentro da pasta /app; 55. Asrotasesto definidas no arquivo /app/config/routing [_dev] .yml e possvel criar atalhos; 56. Autoloading mais universal, mais rpido e independente de necessidade de limpeza de cache; 57. Trs tipos de configuraes:Anotaes , PHP e YAML 58. How to get started?
Fabien Potencier publicado em http://symfony.com/blog/symfony-2-0 59. Referncias
60. http://symfony.com/blog/symfony-2-0 61. Parte II: baby steps
62. Bundles automticos com doctrine2;
63. Sincronizao com banco de dados; 64. Operaes CRUD; 65. Instalao do Symfony2 Framework
67. Passo 3:descompactarna pasta apropriada para aplicaes no servidor web; 68. Instalao do Symfony2 Framework
69. http://localhost/Symfony/web/config.php 70. Pgina de boas vindas: 71. Bundlesautomticos com doctrine2
73. Consoledo Symfony: app/console 74. Bundles automticos com doctrine2 Passo 1: criar um bundle
76. 2. Name 77. 3. Target directory 78. 4. Configuration format 79. 5. Automatic options... Obs: Cria-se um bundle apenasUMAvez 80. Exemplo de umbundlecriado automaticamente:Ifpi/Bundles/DisciplinasBundle Estrutura de diretrios IfpiBundlesDisciplinasBundle: resource: "@IfpiBundlesDisciplinasBundle/Controller/" type:annotation prefix:/ Rotacriada em /app/config/routing.yml public function registerBundles() {....newIfpiBundlesDisciplinasBundleIfpiBundlesDisciplinasBundle(),); Bundle registrado no app/appKernel.php 81. Bundles automticos com doctrine2 Passo 2: criar entidades ( Models )
82. Configuraes: 83. 1. Entity Shortcut Name 84. 2. Configuration format 85. 3. Fields [] 86. Exemplo: Entidade Disciplina Entidade gerada:Arquivo gerado: 87. Exemplo: Entidade Disciplina 88. Bundles automticos com doctrine2 Passo 3:criarbanco de dados
89. Observaes :
91. A configurao do banco pode ser acessada:
92. Via arquivo: /var/www/symfony/app/config/parameters.ini 93. Bundles automticos com doctrine2 Passo 4: atualizar o schema do banco
95. Comando2: executar o comando SQL criado; Obs.: faa isso quando todas as entidades estiverem prontas! 96. Resultado do comando... 97. Bundles automticos com doctrine2 Passo 5: gerar CRUD
Shortcut name Prefixo para rotas futuras 98. Resultado do comando... Controller Views 99. Rotascriadas automaticamente...
100. /disciplina/
102. {id}/edit [ http://localhost/symfony/web/app_dev.php/disciplina/0/edit ] 103. {id}/delete [ http://localhost/symfony/web/app_dev.php/disciplina/0/delete ] 104. Resultados no browser... Rota padro (index) Rota para exibio (show) Rota para edio (edit) 105. Parte III: Afinandoa aplicao...
106. Mapeamento de associaes 107. Validando dados .
108. Existem vrios tipos de validao;
110. validation: { enable_annotations: true } 111. Tipos de validao Basic Constraints These are the basic comstraints: use them to assert very basic things about the value of properties or the return value of methods on your object. NotBlank Blank NotNull Null True False Type String Constraints Email MinLength MaxLength Url Regex Ip Number Constraints Max Min Date Constraints Date DateTime Time Collection Constraints Choice Collection UniqueEntity Language Locale Country File Constraints File Image 112. Algumas validaes // src/Ifpi/Bundle/DisciplinasBundle/Aluno.php use SymfonyComponentValidatorConstraints as Assert; class Aluno { /** * @AssertNotBlank(); * @AssertMax(limit = 10, message = "O valor para mdia no pode ultrapassar o limite de DEZ.") * @AssertMin(limit = 0, message = "O valor para mdia no pode ser inferior que ZERO.") */ private $media; } Valor Mximo e Mnimo de um atributo @AssertEmail( *message = "The email '{{ value }}' is not a valid email.", *checkMX = true * ) protected $email; Validao de e-mail para um atributo /** * @AssertDate() */ protected $dataNasc; Validao de data /** * @AssertChoice(choices = {"masculino", "feminino"}, message = "Escolha um sexo vlido.") */ protected $sexo; Validao de opes Importao comum em todos osexemplos abaixo 113. Validao usando umcallback // src/Acme/BlogBundle/Entity/Author.php use SymfonyComponentValidatorConstraints as Assert; use SymfonyComponentValidatorExecutionContext; /** * @AssertCallback(methods={"isAuthorValid"}) */ class Author { // ... private $firstName; public function isAuthorValid(ExecutionContext $context) { // somehow you have an array of "fake names" $fakeNames = array(); // check if the name is actually a fake name if (in_array($this->getFirstName(), $fakeNames)) { $property_path = $context->getPropertyPath() . '.firstName'; $context->setPropertyPath($property_path); $context->addViolation('This name sounds totally fake!', array(), null); } } } Setup Mtodo 114. Mapeamentode associaes
115. Mais simples e comuns:
117. ManyToMany; 118. OneToOne - Unidirecional
119. Observaes (inclusomanual ):
/** * @ORMOneToOne(targetEntity="Aluno") * @ORMJoinColumn(name="aluno_id", referencedColumnName="id") */ private $aluno; Mapeamento em Notas 121. OneToOne Unidirecional Resultado do comando automtico (CRUD) 122. OneToOne - Bidirecional /** @Entity */ class Aluno { // ... /** * @OneToOne(targetEntity="Notas", mappedBy="aluno") */ private $notas; // ... } 123. OneToOne - Auto-relacionamento /** @Entity */ class Conjuge { // ... /** * @OneToOne(targetEntity="Conjuge") * @JoinColumn(name="conjuge_id", referencedColumnName="id") */ private $conjuge; // } 124. OneToMany -Bidirecional /** @Entity */ class Produto { // ... /** * @OneToMany(targetEntity="Funcionalidade", mappedBy="produto") */ private $funcionalidades; // ... } /** @Entity */ class Funcionalidade { // ... /** * @ManyToOne(targetEntity="Produto") * @JoinColumn(name="produto_id", referencedColumnName="id") */ private $produto; // ... } 125. ManyToMany - Bidirecional /** @Entity */ class Usuario { // ... /** * @ManyToMany(targetEntity="Grupo") * @JoinTable(name="gruposUsuarios", * joinColumns={@JoinColumn(name="usuario_id", referencedColumnName="id")}, * inverseJoinColumns={@JoinColumn(name="grupo_id", referencedColumnName="id")} * ) */ private $grupos; // ... } 126. ManyToMany - Bidirecional /** @Entity */ class Grupo { // ... /** * @ManyToMany(targetEntity="Usuario", mappedBy="grupos") */ private $usuarios; // ... } 127. Prtica Com base no diagrama acima, faa o que se pede abaixo usando o framework Symfony2:
128. Crie regras de validao para os campos: vTelefone, vRaca, bPedigree e vCor; Faa tambm com que o campo tHora aceite apenas o intervalo entre 08:00 e 18:00 horas. 129. Referncias