Symfony2中如何创建一个页面

本文详细介绍了如何使用Symfony2框架创建Bundle,包括创建Bundle文件、注册文件、配置自动装载器、创建Controller、模板以及路由等内容。同时,阐述了Bundle系统、环境配置以及目录结构的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 创建Bundle

命令为:php app/console generate:bundle --namespace=Acme/HelloBundle --format=yml

 这个命令会向app/AppKernel.php中增加如下代码:

// app/AppKernel.php

public function registerBundles()

{

    $bundles = array(

        // ...

        new Acme\HelloBundle\AcmeHelloBundle(),

    );

    // ...

    return $bundles;

}

他的意思是在app注册一个bundle (类似于插件)

1.创建路由

# app/config/routing.yml

AcmeHelloBundle:

    resource: "@AcmeHelloBundle/Resources/config/routing.yml"

    prefix:   /

# src/Acme/HelloBundle/Resources/config/routing.yml

hello:

    pattern:  /hello/{name}

    defaults: { _controller: AcmeHelloBundle:Hello:index }

app/configsrc/Acme下 的Resources/config注册一个路由。

2.创建Controller 一个控制以及功能函数

// src/Acme/HelloBundle/Controller/HelloController.php

namespace Acme\HelloBundle\Controller;

use Symfony\Component\HttpFoundation\Response;

class HelloController

{

}

// src/Acme/HelloBundle/Controller/HelloController.php

// ...

class HelloController

{

    public function indexAction($name)

    {

        return new Response('<html><body>Hello '.$name.'!</body></html>');

    }

}

在src/Acme/下创建功能以及请求的控制函数

3.创建模板(可选)

// src/Acme/HelloBundle/Controller/HelloController.php

namespace Acme\HelloBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class HelloController extends Controller

{

    public function indexAction($name)

    {

        return $this->render('AcmeHelloBundle:Hello:index.html.twig', array('name' => $name));

        // render a PHP template instead

        // return $this->render('AcmeHelloBundle:Hello:index.html.php', array('name' => $name));

    }

}

往src/Acmecontroller下注册一个模板。

{# src/Acme/HelloBundle/Resources/views/Hello/index.html.twig #}

 {% extends '::base.html.twig' %}

 {% block body %}

     Hello {{ name }}!

 {% endblock %}

{# app/Resources/views/base.html.twig #}

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <title>{% block title %}Welcome!{% endblock %}</title>

        {% block stylesheets %}{% endblock %}

        <link rel="shortcut icon" href="{{ asset('favicon.ico') }}" />

    </head>

    <body>

        {% block body %}{% endblock %}

        {% block javascripts %}{% endblock %}

    </body>

</html>

src/AcmeResources/view  下写模板

The Directory Structure

· app/: This directory contains the application configuration;

· src/: All the project PHP code is stored under this directory;

· vendor/: Any vendor libraries are placed here by convention;

· web/: This is the web root directory and contains any publicly accessible files;

The Web Directory

// web/app.php

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是一个可以用Kernel类,AppKernel来启动平台的php文件。

http://localhost/app.php/hello/Ryan http://localhost/hello/Ryan 由于app.php文件在内部运行,所以上边的两个url是相等的。

The Application (app) Directory

AppKernel class is  the core of  application 并且负责所有的配置。AppKernel class 需要实现registerBundles(),registerContainerConfiguration()以方便系统能了解/控制整个系统。

Autoloading:负责配置自动装载器(它将自动从src/和第三方库vendor/下装载)因为有了自动装载器,你不必用include 或者requireSymfony2会用这个类的空间来判断他的位置并且自动包含代表你片刻需要的实例的那个类。自动装载器已经被配置到src下的你的php类下,为了自动的工作。类的名称和路径文件都需要遵循下面的格式。

Class Name:

    Acme\HelloBundle\Controller\HelloController

Path:

src/Acme/HelloBundle/Controller/HelloController.php

当引入第三方库文件的时候,你需要担心你的autoload.php 文件,其他时候不需要担心。

The Bundle System

 An application is made up of bundles as defined in the registerBundles() method of the AppKernel class:

// app/AppKernel.php

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\DoctrineBundle\DoctrineBundle(),

        new Symfony\Bundle\AsseticBundle\AsseticBundle(),

        new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),

        new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),

    );

    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;

}

A bundle can live anywhere as long as it can be autoloaded (via the autoloader configured at app/autoload.php).

Creating a Bundle

1.创建一个bundle文件

// src/Acme/TestBundle/AcmeTestBundle.php

namespace Acme\TestBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class AcmeTestBundle extends Bundle

{

}

2.创建注册文件

// app/AppKernel.php

public function registerBundles()

{

    $bundles = array(

        // ...

        // register your bundles

        new Acme\TestBundle\AcmeTestBundle(),

    );

    // ...

    return $bundles;

}

然后可以用命令php app/console generate:bundle --namespace=Acme/TestBundle来创建相应的文件。比如基本的格式化的controllertemplate和路由源文件。

无论什么时候创建一个bundle或者用一个第三方的bundle,都要确保你的bundle已经注册过了。

Bundle Directory Structure

· Controller/包含bundle所有的控制文件。

· Resources/config/包含所有的配置文件,包括路由的配置文件。

· Resources/views/容纳所有的模板文件。

· Resources/public/包含所有的web资产,通过命令行资产来被复制着。

· Tests/容纳了所有的测试文件。

Application Configuration

   主配置文件位于app/config/下。

   每一个上层元素(像framework或者twig)都给每部分的bundle定义了配置。比如:这个framework键定义了核心SymfonyframewokBundle的配置并且包含了路由,模板和其他核心系统的配置。

   从现在开始,不必担心每一部分的特殊配置选项。配置文件用明智的默认值配置。随着你更多的阅读和查阅Symfony2,你将会学习到关于每一个特性的特殊的配置选项。

  三种配置文件的优缺点:

  Xml:选比yaml更强大,更能完全支持ide

  Yaml:简单,易读,清晰。

  Php:更强大但是不如标准配置格式易读。

Environments

一个Symfony2项目通常有三种开发环境。(devtestprod

通过前端控制器,可以访问应用。

由于prod环境为了提高速度,这些配置,路由,以及twig模板都被编译到php类并且被缓存了。为了看在这些环境下的变化,你需要清空缓存以便于重新编译。

php app/console cache:clear --env=prod --no-debug

环境的配置:如果你打开web/app.php,你将会发现他用prod被明智的配置。你可以通过复制文件来建立一个新的前端控制,并且将prod改成其他的数值。

$kernel = new AppKernel('prod', false);

  当自动运行tests时,测试环境被占用,它不能通过浏览器直接访问,请看测试章节来获取更详细的资料。

Environment Configuration

AppKernel类负责你实际加载选择的配置文件

// app/AppKernel.php

public function registerContainerConfiguration(LoaderInterface $loader)

{

    $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');

}

每个环境都装在他自己的配置文件,下边是开发环境的配置文件。

# app/config/config_dev.yml

imports:

    - { resource: config.yml }

framework:

    router:   { resource: "%kernel.root_dir%/config/routing_dev.yml" }

    profiler: { only_exceptions: false }

# ...

上述代码的入口键值和phpinclude状态很相像,它保证了主要的配置先被加载进来。文件的剩余部分为以后增长的log和设置(可用来引导开发环境)分配设置。

Prod test 环境都遵循相同的模式:每个环境引入基本的配置文件然后为他们需要的特殊环境需改配置值。一旦你自己重新配置或者定制,这就只是一个会话。

Summary

 现在你已经看到Symfony2的每个基本的方面,然后开始充满希望的发现它的容易和方便。然而仍然有很多属性,请确保计入如下的基本点:

1.创建页面是一个三步的进程(包括路由,控制器以及可选择的模板)

2.每个项目都包含一些主要的目录:web/(包括web资产和前端控制器),app(配置),src/(你的bundles),和vendor(第三方主要代码)(也有一个bin/目录来帮助更新vendor库)

3.在Symfony2中的每个功能(包括Symfony2的核心)被组织到一个bundle,他是一系列文件的集合。

4.每个bundle的配置都位于app/config目录下,可以用yamlxml或者php来特殊化。

5.每个环境东可以通过前端控制器来访问并且装载不同的配置文件。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值