Symfony2 Básico

download Symfony2 Básico

If you can't read please download the document

description

Aula introdutória sobre o framework Symfony2.

Transcript of Symfony2 Básico

  • 1. Symfony2 Bsico Prof. Ncio de Lima Veras

2. Parte I: Conhecendo...

  • ...o autor

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

  • Mantm um blog pessoal no qual escreve sobre vrios assuntos, inclusive relacionados com o projeto, tais como:
    • What is Symfony2?
  • 10. Symfony Live Conference, Symfony 2.0, and Dependency Injection

11. The state of YAML in PHP 12. Symfony Service Container: Using XML or YAML to describe Services

  • http://fabien.potencier.org/articles

13. Fabien Potencier

  • Alm do blog pessoal ele tambm participa ativamente do blog oficial do Symfony

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...

  • The involvement of the community for this version of the framework is just incredible. More than 250 developers have contributed in one way or another to this major version through more than 2,000 pull requests

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?

  • First, Symfony2 is a reusable set of standalone, decoupled, and cohesive PHP components that solve common web development problems

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?

  • If you look around, every single framework seems to implement the MVC pattern. And most of them are advertised as MVC frameworks... but not Symfony2
    • Porque eu realmente no me importo se o Symfony2 ou NO MVC;
  • And if you like to call Symfony2 an MVC framework, then you should know that Symfony2 is really about providing the tools for the Controller part, the View part, but not the Model part
    • Para voc criar seu modelo faa no brao ou ento use alguma ferramenta ORM, como por exemplo, o Doctrine.
  • I don't like MVC becausethat's not how the web works . Symfony2 is an HTTP framework; it is a Request/Response framework. [...] The fundamental principles of Symfony2 are centered around the HTTP specification

Fabien Potencier publicado em seu blog pessoal (25/10/11) 26. Is Symfony2 an MVC framework?

  • One of the Symfony2 goals is to provide building blocks for other projects. But what do I mean when I say projects? Who are the target users for Symfony2?Everybody : from personal projects to commercial ones; and Open-Source ones

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)

  • DependencyInjection

29. EventDispatcher 30. HttpFoundation 31. DomCrawler 32. ClassLoader 33. CssSelector 34. HttpKernel 35. BrowserKit 36. Templating 37. Translation 38. Serializer

  • Validator

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

  • Dependency Injection : pattern extensively and it comes with a built-in Dependency Injection Container. It makes Symfony2 very flexible and easily customizable

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

  • Agora ele manipula apenas UMA aplicao (/app);
    • Propsito: centralizar todos os cdigos em um s lugar (/src), ou seja,simplificao ;
  • Bibliotecas e bundles encontram-se todos juntos na pasta /vendor, inclusive bibliotecas dependentes;

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?

  • First:documentation
    • As you all know, code is not everything. Symfony2 also comes with great documentation. The documentation is made of a " Quick Tour " tutorial, aBook , aCookbook ; but also anindex , a http://symfony.com/doc/current/glossary.html glossary , and areferencesection. And for hardcore documentation, you can have a look at the beautifulAPIdocumentation.
  • Second:download
    • http://symfony.com/download
  • Para quem vem da verso 1:How Symfony2 differs from Symfony1

Fabien Potencier publicado em http://symfony.com/blog/symfony-2-0 59. Referncias

  • http://fabien.potencier.org/article/49/what-is-symfony2

60. http://symfony.com/blog/symfony-2-0 61. Parte II: baby steps

  • Instalao;

62. Bundles automticos com doctrine2;

  • Entidades;

63. Sincronizao com banco de dados; 64. Operaes CRUD; 65. Instalao do Symfony2 Framework

  • Passo 1: checkthat you have installed and configured a Web server (such as Apache) with PHP 5.3.2 or higher;
    • Requirements:http://symfony.com/doc/current/reference/requirements.html
  • 66. Principal:PHP needs to be a minimum version of PHP 5.3.2
  • Passo 2: visite o site ( http://symfony.com/download ) efaa o downloaddoSymfony Standard Edition(com ou semVendors );

67. Passo 3:descompactarna pasta apropriada para aplicaes no servidor web; 68. Instalao do Symfony2 Framework

  • Se a instalao for sem Vendors, voc pode atualizar da seguinte forma:
    • php bin/vendors install
  • Configurao e setup:

69. http://localhost/Symfony/web/config.php 70. Pgina de boas vindas: 71. Bundlesautomticos com doctrine2

    • The Doctrine Project is the home of a selected set of PHP libraries primarily focused on providingpersistence servicesand related functionality.
  • 72. Its prize projects are aObject Relational Mapperand theDatabase Abstraction Layerit is built on top of

73. Consoledo Symfony: app/console 74. Bundles automticos com doctrine2 Passo 1: criar um bundle

  • Comando:app/console generate:bundle
    • Configuraes :
  • 75. 1. Namespace

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 )

  • Comando:app/console generate:doctrine:entity

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

  • Comando:app/console doctrine:database:create

89. Observaes :

    • Este comando apenas precisar ser criado uma nica vez;
  • 90. Ele ir criar uma nova base de dados;

91. A configurao do banco pode ser acessada:

  • Via browser:http://localhost/symfony/web/app_dev.php/_configurator/step/0

92. Via arquivo: /var/www/symfony/app/config/parameters.ini 93. Bundles automticos com doctrine2 Passo 4: atualizar o schema do banco

  • Comandos:
    • app/console doctrine:schema:update dump-sql
  • 94. app/console doctrine:schema:update force
  • Comando1: gerar o SQL e mostrar na tela;

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

  • Comando:app/console doctrine:generate:crud

Shortcut name Prefixo para rotas futuras 98. Resultado do comando... Controller Views 99. Rotascriadas automaticamente...

  • /disciplina [ http://localhost/symfony/web/app_dev.php/disciplina/ ]

100. /disciplina/

    • new [ http://localhost/symfony/web/app_dev.php/disciplina/new ]
  • 101. {id}/show [ http://localhost/symfony/web/app_dev.php/disciplina/0/show ]

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...

  • Validao

106. Mapeamento de associaes 107. Validando dados .

  • Constantemente precisamosvalidar dadosem formulrios na Web;

108. Existem vrios tipos de validao;

    • Exemplo: Um determinado campo no pode deixar de ser preenchido; ou um campo no pode ultrapassar um valor limite de X; ;
  • No symfony2, por padro o validador est habilitado:
    • # app/config/config.yml
  • 109. framework:

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

  • Existem vrios tipos de associaes que incluem uni e bidirecionamento, auto-relacionamento, alm dos mapeamentos especiais;

115. Mais simples e comuns:

    • OneToOne;
  • 116. OneToMany;

117. ManyToMany; 118. OneToOne - Unidirecional

  • Exemplo: Aluno -> Notas

119. Observaes (inclusomanual ):

    • GETTERS e SETTERS;
  • 120. Funo __toString() na entidade Aluno;

/** * @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:

  • Crie o projeto, mapeie as entidades e gere as operaes CRUD conforme o modelo;

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