Symfony(5)Controller
The goal of a controller is always the same: create and return a Response object. Along the way, it might read information from the request, load a database resource, send an email, or set information on the user’s session.
1. Basic
Requests, Controller, Response Lifecycle
1. Each request is handled by a simple front controller file (app.php or app_dev.php) that bootstraps the application.
2. The Router reads information from the request, finds a route that matches that information, and reads the _controller parameter.
3. Controller executes and creates and returns a Response object;
4. The HTTP headers and content of the Response object are sent back to the client.
Route Parameters as Controller Arguments
routing.yml may put more parameters, and we can put default parameters in line of the controller configuration.
acme_hello_homepage:
pattern: /hello/{firstName}/{lastName}
defaults: { _controller: AcmeHelloBundle:Default:index, color:green }
public function indexAction($firstName,$lastName, $color){
//…snip...
}
Some Rules:
a. the order of the controller arguments does not matter, system match the names.
b. each required controller argument must match up with a routing parameter, or we can make the parameter optional
public function indexAction($firstName, $lastName, $color, $foo = ‘bar’){
//…snip...
}
c. Not all routing parameters need to be arguments on my controller
public function indexAction($firstName, $color){}
The Request as a Controller Argument
use Symfony\Component\HttpFoundation\Request;
public function contactAction(Request $request)
{
$form = $this->createForm(new ContactType());
$form->handleRequest($request);
if ($form->isValid()) {
$mailer = $this->get('mailer');
// .. setup a message and send it
// http://symfony.com/doc/current/cookbook/email.html
$request->getSession()->getFlashBag()->set('notice', 'Message sent!');
return new RedirectResponse($this->generateUrl('_demo'));
}
return array('form' => $form->createView());
}
The Base Controller Class
class DefaultController extends Controller{
…snip...
}
2. Common Controller Tasks
Redirecting
public function indexAction(){
return $this->redirect($this->generateUrl(‘homepage’));
}
homepage should be the routing name in routing.yml.
By default, the redirect() method performs a 302(temporary) redirect. To perform a 301(permanent) redirect, we put the second argument.
return $this->redirect($this->generateUrl(‘homepage’), 301);
Or we can do as follow
return new RedirectResponse($this->generateUrl('_demo'));
Forwarding
Instead of redirecting the user’s browser, system makes an internal sub-request and calls the specified controller by forwarding.
public function indexAction($name){
$response = $this->forward(‘AcmeHelloBundle:Hello:fancy’, array(
‘name’ => $name,
‘color’ => ‘green'
));
// we even can modify the response here
return $response;
}
public function fancyAction($name, $color){}
Rending Templates
$content = $this->renderView(..snip...);
return new Response($content);
or
return $this->render('AcmeHelloBundle:Default:index.html.twig', array('name' => $name));
Accessing other Services
$templating = $this->get(‘templating’);
$router = $this->get(‘router’);
$mailer = $this->get(‘mailer’);
List all the services we have
>php app/console container:debug
3. Managing Errors and 404 Pages
Based from the base controller
public function indexAction(){
//retrieve the object from db
$product = …;
if(!$product){
throw $this->createNotFoundException(‘The product does not exist’);
}
…snip...
}
throw new \Exception(‘Went Wrong!’);
4. Managing the Session
Symfony2 stores the attributes in a cookie by using the native PHP sessions.
Sessions
public function indexAction(Request $request){
$session = $request->getSession();
$session->set(‘foo’, ‘bar’);
$foobar = $session->get(‘foobar’);
$filters = $session->get(‘filters’, array()); //default value, empty array()
}
Flash Messages
if($form->isValid()){
$request->getSession()->getFlashBag()->set('notice', 'Message sent!');
return $this->redirect(..snip…);
}
Twig
{% for flashMessage in app.session.flashbag.get(’notice’) %}
<div class=“flash-notice”> {{ flashMessage }} </div>
{% endor %}
The Response Object
$response = new Response(‘Hello’.$name, Response::HTTP_OK);
response = new Response(json_encode(array(’name’=>$name)));
response->headers->set(‘Content-Type’, ‘application/json’);
JsonResponse for json, BinaryFileResponse for file.
The Request Object
$request->query->get(‘page’);
$request->request->get(‘page’);
References:
http://symfony.com/doc/2.4/book/controller.html
- 浏览: 2551182 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
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 396PHP Command Line Tool Recently ... -
Code SonarQube 2019(2)PostgreSQL as Database
2019-07-24 05:32 426Code SonarQube 2019(2)PostgreSQ ... -
Code SonarQube 2019(1)Installation with default H2
2019-07-23 10:42 771Code SonarQube 2019(1)Installat ... -
Auth Solution(3)JWT in Java and PHP Sample
2019-05-03 07:33 314Auth Solution(3)JWT in Java and ... -
Flarum BBS System(2)Docker the BBS
2018-11-20 03:31 657Flarum BBS System(2)Docker the ... -
Flarum BBS System(1)Installation and Introduction
2018-11-18 14:29 506Flarum BBS System(1)Installatio ... -
Grav CMS System(5)Multiple Domains and Certs
2018-11-15 01:48 537Grav CMS System(5)Multiple Doma ... -
Grav CMS System(4)Multiple Domain Sites in HAProxy and HTTPS
2018-11-14 21:33 581Grav CMS System(4)Multiple Doma ... -
Grav CMS System(3)Docker Nginx and PHP
2018-11-14 00:21 461Grav CMS System(3)Docker Nginx ... -
Grav CMS System(1)Install PHP7 on MAC
2018-10-23 21:53 636Grav CMS System(1)Install PHP7 ... -
Laravel PHP Framework(1)Introduction and Installation
2018-08-22 02:47 987Laravel PHP Framework(1)Introdu ... -
JSON Log in PHP and Cloud Watch(1)JSON Format in PHP
2017-12-30 05:31 605JSON Log in PHP and Cloud Watch ... -
PHPRedis Library
2017-03-30 00:32 679PHPRedis Library We can instal ... -
PHP Call Wget Command
2017-03-24 23:35 671PHP Call Wget Command In my PH ... -
PHP XML Writer
2017-03-10 03:59 1458PHP XML Writer PHP XML writer ... -
PHP Redis Client and Cluster
2017-02-16 03:34 653PHP Redis Client and Cluster S ... -
PHP Redis Client and Replica
2017-02-16 01:11 598PHP Redis Client and Replica W ... -
PHP HTTP Library and Error Handling
2017-02-11 06:19 654PHP HTTP Library and Error Hand ... -
PHP ENV and HTTP Extension
2017-01-12 01:04 797PHP ENV and HTTP Extension We ... -
PHP Connect Redis Driver
2016-11-23 00:29 582PHP Connect Redis Driver I was ...
相关推荐
在Symfony2框架中,开发者经常需要在控制器(controller)里获取当前页面的URL,以便执行各种操作,例如生成重定向链接、自定义URL等。Symfony2框架提供了多种获取URL的方法,这些方法可以帮助开发者轻松地获取当前...
5. **数据库集成**: Symfony支持多种数据库抽象层,包括Doctrine和Propel。文档中提供了关于如何使用这些数据库抽象层与数据库交互的指南,包括如何配置和使用ORM(对象关系映射)功能。 6. **测试(Testing)**: ...
Symfony是一个开源的PHP框架,遵循MVC(Model-View-Controller)设计模式,旨在提高开发效率并提供高质量的代码。它的核心特性包括组件化、性能优化、可扩展性和灵活性。Symfony由多个独立的PHP组件组成,这些组件...
- 控制器(Controller):作为中间层,它处理来自用户的请求,并决定用哪个模型处理数据以及使用哪个视图来显示结果。 Symfony框架提供了大量的工具和功能来支持项目的全生命周期管理,例如: - 项目建立:Symfony...
在 Symfony2 中构建博客系统可以帮助初学者理解MVC(Model-View-Controller)架构以及该框架的工作原理。本教程将通过一个名为“symblog”的实例,深入探讨如何利用Symfony2搭建一个完整的博客平台。 ### 1. 安装...
在Symfony中,这被称为MVC(Model-View-Controller)模式: - **模型(Model)**:负责处理业务逻辑和数据操作,通常与数据库交互。 - **控制器(Controller)**:是模型和视图之间的桥梁,接收用户请求,处理数据...
首先,Symfony框架遵循MVC(Model-View-Controller)设计模式,它将业务逻辑、数据处理和用户界面分离开来,提高了代码的可维护性和可重用性。在2.3.1版本中,框架提供了强大的控制器层,使得路由、请求处理和响应...
5. **服务(Services)**:Symfony 通过服务容器提供依赖注入,使得代码更易于测试和维护。所有自定义的服务都可在 `src/Service` 目录下找到,并在 `config/services.yaml` 文件中注册。 6. **配置(Configuration...
3. **控制器(Controller)**: 控制器是处理 HTTP 请求并返回响应的核心部分。在 Symfony 中,控制器通常作为服务来定义,并通过路由系统与 URL 映射。 4. **路由(Routing)**: Symfony 提供了强大的路由系统...
它基于 Model-View-Controller (MVC) 架构模式,提供了一系列强大的工具和组件,帮助开发者快速开发出高质量的 web 应用。在 Symfony 1.2.1 版本中,我们看到了一系列增强和改进,旨在提升开发者的体验和应用的性能...
快速入门的第二部分会详细介绍Symfony2的三个核心概念:The View(视图),The Controller(控制器)和The Architecture(架构)。 视图(The View)是指在Web应用中展示给用户的具体内容。在Symfony框架中,视图...
5. **Twig**:默认的模板引擎,用于分离视图层和业务逻辑。 6. **Security**:提供身份验证和授权机制,确保应用程序的安全性。 7. **Console**:用于创建命令行接口(CLI)工具,方便执行脚本或任务。 8. **...
5. **路由配置**:`app/config/routing.yml`定义了URL到控制器的映射规则。 6. **模板文件**:`app/Resources/views`存放应用的视图模板,这些模板通常使用Twig模板引擎来编写。 7. **控制器**:在`src/AppBundle/...
1. **控制器(Controller)**:在Symfony中,控制器是处理HTTP请求并返回响应的PHP类。它们负责协调应用的不同部分,并将数据传递给视图进行渲染。 2. **服务(Services)**:Symfony的服务容器管理着应用的所有...
它遵循 Model-View-Controller (MVC) 设计模式,提供了丰富的工具和组件,使得开发者可以高效地进行开发工作。尽管这里的中文手册对应的是 Symfony 1 版本,但其核心概念和基本原则在后续版本中依然适用,因此具有极...
Symfony由Fabien Potencier于2005年创建,遵循MVC(Model-View-Controller)架构模式,提供了一整套服务容器、路由、表单处理、HTTP基础和安全性的解决方案。2.6版本是Symfony的一个稳定版本,它包含了大量改进和...