Lecture
Это продолжение увлекательной статьи про symfony .
...
follows.
php bin/console generate:bundle --namespace = Tutorialspoint/DemoBundle
Welcome to the Symfony bundle generator! Are you planning on sharing this bundle across multiple applications? [no]: no Your application code must be written in bundles. This command helps you generate them easily. Give your bundle a descriptive name, like BlogBundle. Bundle name [Tutorialspoint/DemoBundle]: In your code, a bundle is often referenced by its name. It can be the concatenation of all namespace parts but it's really up to you to come up with a unique name (a good practice is to start with the vendor name). Based on the namespace, we suggest TutorialspointDemoBundle. Bundle name [TutorialspointDemoBundle]: Bundles are usually generated into the src/ directory. Unless you're doing something custom, hit enter to keep this default! Target Directory [src/]: What format do you want to use for your generated configuration? Configuration format (annotation, yml, xml, php) [annotation]: Bundle generation > Generating a sample bundle skeleton into app/../src/Tutorialspoint/DemoBundle created ./app/../src/Tutorialspoint/DemoBundle/ created ./app/../src/Tutorialspoint/DemoBundle/TutorialspointDemoBundle.php created ./app/../src/Tutorialspoint/DemoBundle/Controller/ created ./app/../src/Tutorialspoint/DemoBundle/Controller/DefaultController.php created ./app/../tests/TutorialspointDemoBundle/Controller/ created ./app/../tests/TutorialspointDemoBundle/Controller/DefaultControllerTest.php created ./app/../src/Tutorialspoint/DemoBundle/Resources/views/Default/ created ./app/../src/Tutorialspoint/DemoBundle/Resources/views/Default/index.html.twig created ./app/../src/Tutorialspoint/DemoBundle/Resources/config/ created ./app/../src/Tutorialspoint/DemoBundle/Resources/config/services.yml > Checking that the bundle is autoloaded > Enabling the bundle inside app/AppKernel.php updated ./app/AppKernel.php > Importing the bundle's routes from the app/config/routing.yml file updated ./app/config/routing.yml > Importing the bundle's services.yml from the app/config/config.yml file updated ./app/config/config.yml Everything is OK! Now get to work :).
This chapter explains how to create a simple application in the Symfony framework. As discussed earlier, you already know how to create a new project in Symfony.
We can take the example of “student” details. Let us start by creating a project named “student” using the following command.
symfony new student
After executing the command, an empty project is created.
Symfony is based on the Model-View-Controller (MVC) design pattern. MVC is a software approach that separates the application logic from the view. The controller plays an important role in the Symfony Framework. Every web page in the application must be handled by a controller.
The DefaultController class is located in “src / AppBundle / Controller” . There, you can create your own Controller class.
Go to the “src / AppBundle / Controller” folder and create a new StudentController class.
Below is the basic syntax for the StudentController class.
namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
class StudentController {
}
You have now created StudentController. In the next chapter, we will discuss the controller in more detail.
Once the Controller has been created, we need to route it to a specific page. Routing maps the request URI to a specific controller method.
Below is the basic syntax for routing.
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class StudentController {
/**
* @Route("/student/home")
*/
public function homeAction() {
return new Response('Student details application!');
}
}
In the syntax above, @Route (“/ student / home”) is the route. It defines the URL pattern for the page.
homeAction () is the action method, in which you can build the page and return a Response object.
We will look at routing in detail in the next chapter. Now request the URL “http: // localhost: 8000 / student / home”, and it will give the following result.

The controller is responsible for handling every request coming into the Symfony application. The controller reads information from the request. It then creates and returns a response object to the client.
In Symfony, the DefaultController class is located in “src / AppBundle / Controller” . It is defined as follows.
Here, the HttpFoundation component defines an object-oriented layer for the HTTP specification, and FrameworkBundle contains most of the “core” framework functionality.
Request Object
The Request class is an object-oriented representation of the HTTP request message.
Creating a Request Object
A request can be created using the createFromGlobals () method .
use Symfony\Component\HttpFoundation\Request; $request = Request::createFromGlobals();You can simulate a request using Globals. Instead of creating a request based on PHP global variables, you can also simulate a request.
$request = Request::create( '/student', 'GET', array('name' => 'student1') );Here, the create () method creates a request based on a URI, a method, and some parameters.
Overriding the Request Object
You can override PHP global variables using the overrideGlobals () method . It is defined as follows.
$request->overrideGlobals();Accessing the Request Object
The web page can be accessed inside the controller (action method) using the base controller's getRequest () method.
$request = $this->getRequest();Identifying the Request Object
If you want to identify the request in your application, the PathInfo method will return a unique identifier for the request URL. It is defined as follows.
$request->getPathInfo();Response Object
The only requirement of a controller is to return a Response object. The Response object contains all the information from a given request and sends it back to the client.
Below is a simple example.
Example
use Symfony\Component\HttpFoundation\Response; $response = new Response(‘Default'.$name, 10);You can define the Response object in JSON as follows.
$response = new Response(json_encode(array('name' => $name))); $response->headers->set('Content-Type', 'application/json');Response Constructor
The constructor takes three arguments —
Below is the basic syntax.
use Symfony\Component\HttpFoundation\Response;
$response = new Response(
'Content',
Response::HTTP_OK,
array('content-type' => 'text/html')
);
For example, you can pass the content argument as,
$response->setContent(’Student details’);
In the same way, you can pass the other arguments too.
You can send the response to the client using the send () method . It is defined as follows.
$response->send();
To redirect the client to another URL, you can use the RedirectResponse class.
It is defined as follows.
use Symfony\Component\HttpFoundation\RedirectResponse;
$response = new RedirectResponse('http://tutorialspoint.com/');
A single PHP file that handles every request coming into your application. The FrontController performs the routing of different URLs to the internal parts of the application.
Below is the basic syntax of a FrontController.
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$request = Request::createFromGlobals();
$path = $request->getPathInfo(); // the URI path being requested
if (in_array($path, array('', '/'))) {
$response = new Response(’Student home page.');
} elseif (‘/about’ === $path) {
$response = new Response(’Student details page’);
} else {
$response = new Response('Page not found.', Response::HTTP_NOT_FOUND);
}
$response->send();
Here, the in_array () function looks for a specific value in an array.
Routing maps a request URI to a specific controller method. In general, any URI consists of the following three parts:
For example, in the URI / URL http://www.tutorialspoint.com/index?q=data, www.tutorialspoint.com is the host name segment, index is the path segment, and q = data is the query segment. In general, routing checks the page segment against a set of constraints. If a constraint matches, it returns a set of values. One of the main values is the controller.
Annotations play an important role in configuring a Symfony application. Annotation simplifies configuration by declaring the configuration right within the code itself. An annotation is nothing but a way of providing meta-information about a class, methods, and properties. Routing makes wide use of annotations. Even though routing can be done without annotations, annotations make routing much simpler.
Below is an example of an annotation.
/**
* @Route(“/student/home”)
*/
public function homeAction() {
// ...
}
Consider the StudentController, class created in the “student” project.
// src/AppBundle/Controller/StudentController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class StudentController extends Controller {
/**
* @Route(“/student/home”)
*/
public function homeAction() {
// ...
}
/**
* @Route(“/student/about”)
*/
public function aboutAction() {
}
}
Here, routing is done in two stages. If you go to / student / home , the first route matches, and then homeAction () executes . Otherwise, if you go to / student / about , the second route is found, and then aboutAction () executes .
Suppose you have a numbered list of student records with URLs like / student / 2 and / student / 3 for pages 2 and 3 respectively. Then, if you want to change the route path, you can use wildcard formats.
// src/AppBundle/Controller/BlogController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class StudentController extends Controller {
/**
* @Route(“/student/{page}", name = “student_about”, requirements = {"page": "\d+"})
*/
public function aboutAction($page) {
// ...
}
}
Here, \ d + is a regular expression that matches a digit of any length.
You can assign a default value to a placeholder in routing. It is defined as follows.
// src/AppBundle/Controller/BlogController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class StudentController extends Controller {
/**
* @Route(“/student/{page}", name = “student_about”, requirements = {"page": "\d+"})
*/
public function aboutAction($page = 1) {
// ...
}
}
Here, if you go to / student, the student_about route will match, and $ page will default to 1.
If you want to redirect the user to another page, use the redirectToRoute () and redirect () methods.
public function homeAction() {
// redirect to the "homepage" route
return $this->redirectToRoute('homepage');
// redirect externally
\return $this->redirect('http://example.com/doc');
}
To generate a URL, consider the route name, student name, and the wildcard, student names, used in the path for that route. The full listing for generating the URL is defined as follows.
class StudentController extends Controller {
public function aboutAction($name) {
// ...
// /student/student-names
$url = $this->generateUrl(
‘student_name’,
array(‘name’ =>
’student-names’)
);
}
}
Consider the following simple routing example in the StudentController class.
Project: '.$name.'