Symfony(2)Tour - Views Controllers Bundles
1. Twig Twig Twig
http://twig.sensiolabs.org/documentation
A Twig template is a text file that can generate any type of content (HTML, CSS, JavaScript, XML, CSV…)
{# array( ‘user’ => array(’name’ => ‘Fabien’)) #}
{{ user.name }}
or
{{ user[’name’] }}
{# array(‘user’ => new User(‘Fabien')) #}
{{ user.name }}
{{ user.getName() }}
Decorating Templates
layout.html.twig
<div>
{% block content %}
{% endblock %}
</div>
hello.html.twig
{% extends “AcmeDemoBundle::layout.html.twig” %}
{% block content %}
<h1>Hello {{ name }} !</h1>
{% endblock %}
Using Tags, Filters, and Functions
{{ article.title|trim|capitalize }}
This is really powerful, Embedding other Controllers
{# index.html.twig #}
{{ render(controller(“AcmeDemoBundle:Demo:topArticles”, {’num’: 10})) }}
Creating Links between Pages
<a href=“{{ path(‘_demo_hello’, { ’name’ : ‘Carl’ }) }}”>Go and have Fun!</a>
That name _demo_hello will match the name of the annotation in routing.
Including Assets: Images, JavaScripts and Stylesheets
<link rel="icon" sizes="16x16" href="{{ asset('favicon.ico') }}" />
<link rel="stylesheet" href="{{ asset('bundles/acmedemo/css/demo.css') }}" />
2. The Controller
Using Formats
Change the annotation as follow:
/**
* @Route("/hello/{name}", defaults={"_format"="xml"}, name="_demo_hello")
* @Template()
*/
public function helloAction($name)
{
return array('name' => $name);
}
Directly write some codes in the Twig template
<hello>
<name>{{ name }}</name>
</hello>
If we plan to support multiple format at one time, we need to add parameter in the routing.
The Routing annotation will changes as follow:
/**
* @Route(
* "/hello/{name}.{_format}",
* defaults={"_format"="html"},
* requirements = { "_format" = "html|xml|json"},
* name="_demo_hello")
* @Template()
*/
Redirecting and Forwarding
return $this->redirect($this->generateUrl(‘_demo_hello’, array(‘name’ =>”Sillycat’) ) );
return $this->forward(‘AcmeDemoBundle:Hello:index’, array(
‘name’ => $name,
‘color’ => ‘green'
));
Displaying Error Pages
404
throw $this->createNotFoundException();
500
throw new \Exception('Something went wrong!’);
It is very important to put \ before Exception.
Getting Information from the Request
If our action has an argument that type is Symfony\Component\HttpFoundation\Request, we can have the Request info.
use Symfony\Component\HttpFoundation\Request;
public function someAction(Request $request){
$request->isXmlHttpRequest(); //is it an Ajax request?
$request->query->get(‘page’); //get a $_GET parameter
$request->request->get(‘page’); //get a $_POST parameter
}
In the template, we can also access the variables in $request like this.
{{ app.request.query.get(‘page’) }}
{{ app.request.parameter(‘page’) }}
Persisting Data in the Session
HTTP protocol is stateless, between 2 requests, Symfony2 stores the attributes in a cookie by using native PHP sessions.
public function someAction(Request $request){
$session = $this->request->getSession();
$session->set(‘username’, ‘Carl’);
$username = $session->get(‘username’);
$username = $session->get(‘username’, ’DefaultName’); //get with default value
}
Before redirecting, we can store the Error Message/Successful Message in “Flash Messages”.
$session->getFlashBag()->add(‘’notice’,’congratulations,your action is succeeded!’);
In the template
<div> {{ app.session.flashbag.get(‘notice’) }} </div>
Caching Resources
Put that in the annotation right after @Template()
/**
* @Route(…)
* @Template()
* @Cache(maxage=“86400”)
*/
The unit for that cache configuration is second, 86400 is a day.
3. The Architecture
app - application configuration
src
vendor - the third-party dependencies
web - web root
3.1 How the PHP Controller Start
Controller will load the app/AppKernel.php, In side the AppKernel.php, it will provide at least 2 methods.
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
3.2 Understanding the Bundle System
Bundle is a plugin, it is called bundle because everything is a bundle in Symfony2. You can use pre-built features packaged in third-party bundles or distribute your own bundles.
Registering a Bundle
AppKernel — registerBundles()
Each bundle is a directory that contains a single Bundle class that describes it.
For example, in the src directory, we have Acme\DemoBundle\AcmeDemoBundle.php
<?php
namespace Acme\DemoBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AcmeDemoBundle extends Bundle
{
}
Then we have this line in the AppKernel.php
$bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
For the third party Bundle
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
vendor/symfony/symfony/src/Symfony/Bundle
Configuring a Bundle
Look at app/config/config.yml.
imports:
- { resource: parameters.yml }
- { resource: security.yml }
framework:
#esi: ~
#translator: { fallback: "%locale%" }
secret: "%secret%”
…snip…
# Twig Configuration
twig:
debug: "%kernel.debug%”
framework configures FrameworkBundle, twig configures TwigBundle.
DEV environment loads config_dev.yml and overwrites the config.yml.
Extending a Bundle
Logical File Names
@BUNDLE_NAME/path/to/file;
@AcmeDemoBundle/Controller/SecuredController.php
Logical Controller Names
BUNDLE_NAME:CONTROLLER_NAME:ACTION_NAME, for example, AcmeDemoBundle:Welcome:index
Logical Template Names
AcmeDemoBundle:Welcome:index.html.twig ——> src/Acme/DemoBundle/Resources/views/Welcome/index.html.twig
Extending Bundles
http://symfony.com/doc/current/cookbook/bundles/inheritance.html
Using Vendors
Symfony2 loads a lot of yaml and XML, we only do parse at the first request and then cache the plain PHP codes in app/cache. In the DEV environment, Symfony2 will flush the cache when we change a file.
But in the production environment, we take the responsibility to clear the cache.
app/logs/
Using the Command Line Interface
>php app/console --help
>php app/console -V
Symfony version 2.4.5 - app/dev/debug
>php app/console --env=dev server:run
This command default run PHP built-in server based on development environment.
Go further, read this book http://symfony.com/doc/current/book/index.html
References:
http://symfony.com/doc/current/quick_tour/the_view.html
http://symfony.com/doc/current/cookbook/bundles/inheritance.html
http://symfony.com/doc/current/book/index.html
- 浏览: 2486508 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
发表评论
-
PHP Command Line Tool
2019-08-17 05:06 356PHP Command Line Tool Recently ... -
Code SonarQube 2019(2)PostgreSQL as Database
2019-07-24 05:32 376Code SonarQube 2019(2)PostgreSQ ... -
Code SonarQube 2019(1)Installation with default H2
2019-07-23 10:42 734Code SonarQube 2019(1)Installat ... -
Auth Solution(3)JWT in Java and PHP Sample
2019-05-03 07:33 284Auth Solution(3)JWT in Java and ... -
Flarum BBS System(2)Docker the BBS
2018-11-20 03:31 606Flarum BBS System(2)Docker the ... -
Flarum BBS System(1)Installation and Introduction
2018-11-18 14:29 462Flarum BBS System(1)Installatio ... -
Grav CMS System(5)Multiple Domains and Certs
2018-11-15 01:48 494Grav CMS System(5)Multiple Doma ... -
Grav CMS System(4)Multiple Domain Sites in HAProxy and HTTPS
2018-11-14 21:33 554Grav CMS System(4)Multiple Doma ... -
Grav CMS System(3)Docker Nginx and PHP
2018-11-14 00:21 428Grav CMS System(3)Docker Nginx ... -
Grav CMS System(1)Install PHP7 on MAC
2018-10-23 21:53 543Grav CMS System(1)Install PHP7 ... -
Laravel PHP Framework(1)Introduction and Installation
2018-08-22 02:47 955Laravel PHP Framework(1)Introdu ... -
JSON Log in PHP and Cloud Watch(1)JSON Format in PHP
2017-12-30 05:31 565JSON Log in PHP and Cloud Watch ... -
PHPRedis Library
2017-03-30 00:32 644PHPRedis Library We can instal ... -
PHP Call Wget Command
2017-03-24 23:35 640PHP Call Wget Command In my PH ... -
PHP XML Writer
2017-03-10 03:59 1424PHP XML Writer PHP XML writer ... -
PHP Redis Client and Cluster
2017-02-16 03:34 613PHP Redis Client and Cluster S ... -
PHP Redis Client and Replica
2017-02-16 01:11 557PHP Redis Client and Replica W ... -
PHP HTTP Library and Error Handling
2017-02-11 06:19 604PHP HTTP Library and Error Hand ... -
PHP ENV and HTTP Extension
2017-01-12 01:04 762PHP ENV and HTTP Extension We ... -
PHP Connect Redis Driver
2016-11-23 00:29 549PHP Connect Redis Driver I was ...
相关推荐
symfony-demo-mater
symfony-json-request-transformer, 用于解码JSON编码请求内容的Symfony 2事件侦听器 symfony-json-request-transformer用于解码JSON编码请求内容的Symfony事件侦听器。 请阅读关于这里知识库的博客文章,位于 /...
Laravel开发-symfony-web-uploader 简化文件上传到外部API的PHP库
Ajax-Symfony-3.4-Blog.zip,symfony 3.4博客,带有管理仪表板ajax和许多其他功能!,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。它用于创建动态网页,其中网页的小...
symfony-console-form, 为控制台命令输入使用Symfony窗体 控制台窗体By Noback 这个包包含一个Symfony包和一些工具,允许你使用Symfony表单类型来定义和交互处理来自的用户输入。安装composer require ...
Api-symfony-flex-backend.zip,带有symfony flex的rest api这是什么,一个api可以被认为是多个软件设备之间通信的指导手册。例如,api可用于web应用程序之间的数据库通信。通过提取实现并将数据放弃到对象中,api简化...
Api-symfony-angular-todomvc.zip,使用angularjs和symfony rest editionsymfony angular实现todomvc,一个api可以被认为是多个软件设备之间通信的指导手册。例如,api可用于web应用程序之间的数据库通信。通过提取...
Ajax-Symfony-3-ERPMedical.zip,足病患者的ERP医疗。包括:病人管理,病史,医学研究,会计,预约,日历,经济统计。,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。...
快速开始$ git clone https://github.com/tulik/symfony-4-docker-runtime-env.git$ cd symfony-4-docker-runtime-env$ docker-compose up等待容器启动,然后访问配置Xdebug 如果使用以外的其他IDE,请转到Xdebug...
Symfony演示应用 一个具有基本用户管理,REST / GraphQL API和OAuth / JWT身份验证的Symfony演示应用程序。 MsgPHP是一个项目,旨在为您...composer create-project msgphp/symfony-demo-app cd symfony-demo-app # Da
使用composer require --dev mikedevelper/symfony-helpers-bundle安装composer require --dev mikedevelper/symfony-helpers-bundle 添加文件config/dev/mikedevs_helpers.yaml 并把 mikedevs_helpers: yml_path...
版本5将于今年11月发布。...Symfony Slack机器人 简单的Symfony 3和4捆绑包,用于通过向Slack发送可自定义的... " wow-apps/symfony-slack-bot " : " ^4.0 " } 要么 $ composer require wow-apps/symfony-slack-bot 第2步
Symfony PHP CodeSniffer编码标准一种与编码标准进行对照的,最初是从-disappeared- opensky / Symfony2-coding-standard标准存储库无耻地复制而来的。安装作曲家该标准可以与依赖性管理器一起安装。将编码标准安装...
Symfony集装箱模型 该容器使您可以在Symfony依赖项注入容器中模拟服务。 它在功能测试中特别有用。... composer require "ramunasd/symfony-container-mocks" 或编辑您的composer.json: { "require" : { "ramun
docker-symfony-mysql-nginx-example 带有Symfony,nginx和MySQL的Docker示例使用说明git clone ...data, a member of the www-data groupsudo chown -R $(whoami):1000 app# bri
Symfony代码库包含遵循规范和API的真实示例(CRUD,...入门$ git clone https://github.com/slashfan/symfony-realworld-example-app$ cd symfony-realworld-example-app运行项目(使用docker) 第一次运行时: $ make
$ composer require m-adamski/symfony-schedule-bundle 如何使用它? 捆绑包提供了通过配置指定文件来管理CRON作业的功能。 我们需要创建实现Adamski\Symfony\ScheduleBundle\Model\ManagerInterface接口的类。 ...
发电机Symfony带来的... 为了使其可用,您将需要克隆此项目并运行以下命令: git clone https://github.com/wrousseau/generator-symfony-with-benefitscd generator-symfony-with-benefitsnpm link使用它创建并cd到
Symfony控制台表格马蒂亚斯·诺巴克(Matthias ...安装composer require matthiasnoback/symfony-console-form 在Symfony应用程序的内核中启用Matthias\SymfonyConsoleForm\Bundle\SymfonyConsoleFormBundle 。 <?...
欢迎使用Symfony标准版-一个功能齐全的Symfony2应用程序,您可以将其用作新应用程序的框架。 本文档包含有关如何下载,安装和开始使用Symfony的信息。 有关更详细的说明,请参见Symfony文档中的“一章。 安装标准...