`
sillycat
  • 浏览: 2551927 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Symfony(2)Tour - Views Controllers Bundles

    博客分类:
  • PHP
 
阅读更多

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


分享到:
评论

相关推荐

    symfony-demo-mater

    2. **控制器(Controllers)**:控制器负责处理请求并生成响应。它们通常位于 `src/Controller` 目录下,如 `DefaultController.php`,包含处理特定请求的行动方法。 3. **视图(Views)**:视图负责呈现数据,通常...

    symfony-json-request-transformer, 用于解码JSON编码请求内容的Symfony 2事件侦听器.zip

    symfony-json-request-transformer, 用于解码JSON编码请求内容的Symfony 2事件侦听器 symfony-json-request-transformer用于解码JSON编码请求内容的Symfony事件侦听器。 请阅读关于这里知识库的博客文章,位于 /...

    Laravel开发-symfony-web-uploader

    在本文中,我们将深入探讨如何使用"Laravel开发-symfony-web-uploader"这一工具来简化在Laravel项目中上传文件到外部API的过程。这个库是专门为Laravel框架设计的,目的是利用Symfony的WebProfiler组件来优化文件...

    Ajax-Symfony-3.4-Blog.zip

    Ajax-Symfony-3.4-Blog.zip,symfony 3.4博客,带有管理仪表板ajax和许多其他功能!,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。它用于创建动态网页,其中网页的小...

    symfony-console-form, 为控制台命令输入使用Symfony窗体.zip

    symfony-console-form, 为控制台命令输入使用Symfony窗体 控制台窗体By Noback 这个包包含一个Symfony包和一些工具,允许你使用Symfony表单类型来定义和交互处理来自的用户输入。安装composer require ...

    Api-symfony-flex-backend.zip

    Api-symfony-flex-backend.zip,带有symfony flex的rest api这是什么,一个api可以被认为是多个软件设备之间通信的指导手册。例如,api可用于web应用程序之间的数据库通信。通过提取实现并将数据放弃到对象中,api简化...

    Api-symfony-angular-todomvc.zip

    Api-symfony-angular-todomvc.zip,使用angularjs和symfony rest editionsymfony angular实现todomvc,一个api可以被认为是多个软件设备之间通信的指导手册。例如,api可用于web应用程序之间的数据库通信。通过提取...

    Ajax-Symfony-3-ERPMedical.zip

    Ajax-Symfony-3-ERPMedical.zip,足病患者的ERP医疗。包括:病人管理,病史,医学研究,会计,预约,日历,经济统计。,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。...

    symfony-easy-admin

    **标题:“symfony-easy-admin”** **描述:“安装、应用概述、管理控制台、lodin-密码:admin-admin”** 在IT行业中,`symfony-easy-admin` 是一个基于 Symfony 框架构建的开源后台管理系统。它为开发者提供了一...

    symfony-4-docker-env:Symfony的Docker环境。 PHP-FPM,NGINX SSL代理,MySQL,LEMP

    快速开始$ 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-demo-app:具有基本用户管理功能的Symfony演示应用程序

    Symfony演示应用 一个具有基本用户管理,REST / GraphQL API和OAuth / JWT身份验证的Symfony演示应用程序。 MsgPHP是一个项目,旨在为您...composer create-project msgphp/symfony-demo-app cd symfony-demo-app # Da

    symfony-helpers-bundle

    使用composer require --dev mikedevelper/symfony-helpers-bundle安装composer require --dev mikedevelper/symfony-helpers-bundle 添加文件config/dev/mikedevs_helpers.yaml 并把 mikedevs_helpers: yml_path...

    symfony-slack-bot:现代且简单的软件包,用于通过传入的Symfony 3和4的Web挂钩向Slack发送可定制的消息

    版本5将于今年11月发布。...Symfony Slack机器人 简单的Symfony 3和4捆绑包,用于通过向Slack发送可自定义的... " wow-apps/symfony-slack-bot " : " ^4.0 " } 要么 $ composer require wow-apps/symfony-slack-bot 第2步

    Symfony-coding-standard:Symfony编码标准的开发存储库

    Symfony PHP CodeSniffer编码标准一种与编码标准进行对照的,最初是从-disappeared- opensky / Symfony2-coding-standard标准存储库无耻地复制而来的。安装作曲家该标准可以与依赖性管理器一起安装。将编码标准安装...

    symfony-container-mocks:Symfony容器,可简化服务模拟

    Symfony集装箱模型 该容器使您可以在Symfony依赖项注入容器中模拟服务。 它在功能测试中特别有用。... composer require "ramunasd/symfony-container-mocks" 或编辑您的composer.json: { "require" : { "ramun

    symfony-api-platform:api-平台,php7.4,RabbitMq

    `symfony-api-platform`是一个基于Symfony框架构建的开源API开发平台,它提供了一整套工具和服务,用于快速、高效地开发RESTful API。`php7.4`是PHP编程语言的一个版本,以其性能提升和新特性的引入而知名。`...

    docker-symfony-mysql-nginx-example:带有Symfony,nginx和MySQL的Docker示例

    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-platform:Symfony API平台教程

    `symfony-api-platform` 是一个基于 Symfony 框架构建的开源项目,专门用于快速开发高质量的 RESTful API。本教程将深入探讨如何使用这个强大的工具集来构建现代Web服务。作为一款JavaScript相关的技术,它允许...

    nb-symfony-templates-plugin:Symfony 2 插件,包含文件和代码模板

    `nb-symfony-templates-plugin` 是一个专为 Symfony 2 框架设计的插件,主要用于 NetBeans IDE。这个插件的目的是为了提升 Symfony 2 开发者的生产力,通过提供预先配置好的文件和代码模板,使得创建和编辑 Symfony ...

    symfony-realworld-example-app:Symfony 5代码库,包含遵循RealWorld规范和API的真实示例(CRUD,auth,高级模式等)

    Symfony代码库包含遵循规范和API的真实示例(CRUD,...入门$ git clone https://github.com/slashfan/symfony-realworld-example-app$ cd symfony-realworld-example-app运行项目(使用docker) 第一次运行时: $ make

Global site tag (gtag.js) - Google Analytics