Symfony – Ajax Control

Symfony – Ajax Control ”; Previous Next AJAX is a modern technology in web programming. It provides options to send and receive data in a webpage asynchronously, without refreshing the page. Let us learn Symfony AJAX programming in this chapter. Symfony framework provides options to identity whether the request type is AJAX or not. Request class of Symfony HttpFoundation component has a method, isXmlHttpRequest() for this purpose. If an AJAX request is made, the current request object”s isXmlHttpRequest() method returns true, otherwise false. This method is used to handle an AJAX request properly in the server side. if ($request->isXmlHttpRequest()) { // Ajax request } else { // Normal request } Symfony also provides a JSON based Response class, JsonResponse to create the response in JSON format. We can combine these two methods to create a simple and clean AJAX based web application. AJAX – Working Example Let us add a new page, student/ajax in student application and try to fetch the student information asynchronously. Step 1 − Add ajaxAction method in StudentController(src/AppBundle/Controller/StudentController.php). /** * @Route(“/student/ajax”) */ public function ajaxAction(Request $request) { $students = $this->getDoctrine() ->getRepository(”AppBundle:Student”) ->findAll(); if ($request->isXmlHttpRequest() || $request->query->get(”showJson”) == 1) { $jsonData = array(); $idx = 0; foreach($students as $student) { $temp = array( ”name” => $student->getName(), ”address” => $student->getAddress(), ); $jsonData[$idx++] = $temp; } return new JsonResponse($jsonData); } else { return $this->render(”student/ajax.html.twig”); } } Here, if the request is AJAX, we fetch student information, encode it as JSON and return it using JsonResponse object. Otherwise, we just render the corresponding view. Step 2 − Create a view file ajax.html.twig in Student views directory, app/Resources/views/student/ and add the following code. {% extends ”base.html.twig” %} {% block javascripts %} <script language = “javascript” src = “https://code.jquery.com/jquery-2.2.4.min.js”></script> <script language = “javascript”> $(document).ready(function(){ $(“#loadstudent”).on(“click”, function(event){ $.ajax({ url: ”/student/ajax”, type: ”POST”, dataType: ”json”, async: true, success: function(data, status) { var e = $(”<tr><th>Name</th><th>Address</th></tr>”); $(”#student”).html(””); $(”#student”).append(e); for(i = 0; i < data.length; i++) { student = data[i]; var e = $(”<tr><td id = “name”></td><td id = “address”></td></tr>”); $(”#name”, e).html(student[”name”]); $(”#address”, e).html(student[”address”]); $(”#student”).append(e); } }, error : function(xhr, textStatus, errorThrown) { alert(”Ajax request failed.”); } }); }); }); </script> {% endblock %} {% block stylesheets %} <style> .table { border-collapse: collapse; } .table th, td { border-bottom: 1px solid #ddd; width: 250px; text-align: left; align: left; } </style> {% endblock %} {% block body %} <a id = “loadstudent” href = “#”>Load student information</a> </br> </br> <table class = “table”> <tbody id = “student”></tbody> </table> {% endblock %} Here, we have created an anchor tag (id: loadstudent) to load the student information using AJAX call. The AJAX call is done using JQuery. Event attached to loadstudent tag activates when a user clicks it. Then, it will fetch the student information using AJAX call and generate the required HTML code dynamically. Step 3− Finally, run the application, http://localhost:8000/student/ajax and click the Load student information anchor tab. Result: Initial Page Result: Page with Student Information Print Page Previous Next Advertisements ”;

Cookies & Session Management

Symfony – Cookies and Session Management ”; Previous Next Symfony HttpFoundation component provides cookie and session management in an object-oriented manner. Cookie provides client-side data storage and it only supports a small amount of data. Usually, it is 2KB per domain and it depends on the browser. Session provides server-side data storage and it supports a large amount of data. Let us see how to create a cookie and session in a Symfony web application. Cookie Symfony provides Cookie class to create a cookie item. Let us create a cookie color, which expires in 24 hours with value blue. The constructor parameter of the cookie class is as follows. name (type: string) – cookie name value (type: string) – cookie value expire (type: integer / string / datetime) – expiry information path (type: string) – the server path in which the cookie is available domain (type: string) – the domain address in which the cookie is available secure (type: boolean) – whether the cookie needs to be transmitted in HTTPS connection httpOnly (type: boolean) – whether the cookie is available only in HTTP protocol use SymfonyComponentHttpFoundationCookie; $cookie = new Cookie(”color”, ”green”, strtotime(”tomorrow”), ”/”, ”somedomain.com”, true, true); Symfony also provides the following string-based cookie creation option. $cookie = Cookie::fromString(”color = green; expires = Web, 4-May-2017 18:00:00 +0100; path=/; domain = somedomain.com; secure; httponly”); Now, the created cookie needs to be attached to the http response object”s header as follows. $response->headers->setCookie($cookie); To get the cookie, we can use Request object as follows. $cookie = $request->cookie->get(”color”); Here, request->cookie is of type PropertyBag and we can manipulate it using PropertyBag methods. Session Symfony provides a Session class implementing SessionInterface interface. The important session API are as follows, start − Starts the session. Session $session = new Session(); $session->start(); invalidate − Clears all session data and regenerates the session ID. set − Stores data in the session using a key. $session->set(”key”, ”value”); We can use any data in the session value, be in simple integer to complex objects. get − Gets data from the session using the key. $val = $session->get(”key”); remove − Removes a key from the session. clear − Removes a session data. FlashBag Session provides another useful feature called FlashBag. It is a special container inside the session holding the data only during page redirection. It is useful in http redirects. Before redirecting to a page, data can be saved in FlashBag instead of a normal session container and the saved data will be available in the next request (the redirected page). Then, the data will be invalidated automatically. $session->getFlashBag()->add(”key”, ”value”); $session->getFlashBag()->get(”key”); Print Page Previous Next Advertisements ”;

Symfony – REST Edition

Symfony – REST Edition ”; Previous Next In any modern application, REST service is one of the core fundamental building blocks. Be it a web-based application or a slick mobile application, the front-end is usually a well designed interface for the back-end REST services. Symfony REST edition provides a readymade template to kick-start our REST based web application. Let us learn how to install a template REST application using Symfony REST edition. Step 1 − Download Symfony REST edition using the following command. composer create-project gimler/symfony-rest-edition –stability=dev path/to/install This will download the Symfony REST edition. Step 2 − Try to configure it by asking some questions. For all the questions, select the default answer except database. For database, select pdo_sqlite. You may need to enable PHP”s sqlite extension, if it is not already installed. Step 3 − Now, run the application using the following command. php app/console server:run Step 4 − Finally, open the application in the browser using http://localhost:8000/. It will produce the following result − Print Page Previous Next Advertisements ”;

Symfony – Unit Testing

Symfony – Unit Testing ”; Previous Next Unit test is essential for ongoing development in large projects. Unit tests will automatically test your application’s components and alert you when something is not working. Unit testing can be done manually but is often automated. PHPUnit Symfony framework integrates with the PHPUnit unit testing framework. To write a unit test for the Symfony framework, we need to set up the PHPUnit. If PHPUnit is not installed, then download and install it. If it is installed properly, then you will see the following response. phpunit PHPUnit 5.1.3 by Sebastian Bergmann and contributors Unit test A unit test is a test against a single PHP class, also called as a unit. Create a class Student in the Libs/ directory of the AppBundle. It is located at “src/AppBundle/Libs/Student.php”. Student.php namespace AppBundleLibs; class Student { public function show($name) { return $name. “ , Student name is tested!”; } } Now, create a StudentTest file in the “tests/AppBundle/Libs” directory. StudentTest.php namespace TestsAppBundleLibs; use AppBundleLibsStudent; class StudentTest extends PHPUnit_Framework_TestCase { public function testShow() { $stud = new Student(); $assign = $stud->show(‘stud1’); $check = “stud1 , Student name is tested!”; $this->assertEquals($check, $assign); } } Run test To run the test in the directory, use the following command. $ phpunit After executing the above command, you will see the following response. PHPUnit 5.1.3 by Sebastian Bergmann and contributors. Usage: phpunit [options] UnitTest [UnitTest.php] phpunit [options] <directory> Code Coverage Options: –coverage-clover <file> Generate code coverage report in Clover XML format. –coverage-crap4j <file> Generate code coverage report in Crap4J XML format. –coverage-html <dir> Generate code coverage report in HTML format. Now, run the tests in the Libs directory as follows. $ phpunit tests/AppBundle/Libs Result Time: 26 ms, Memory: 4.00Mb OK (1 test, 1 assertion) Print Page Previous Next Advertisements ”;

Symfony – Forms

Symfony – Forms ”; Previous Next Symfony provides various in-built tags to handle HTML forms easily and securely. Symfony’s Form component performs form creation and validation process. It connects the model and the view layer. It provides a set of form elements to create a full-fledged html form from pre-defined models. This chapter explains about Forms in detail. Form Fields Symfony framework API supports large group of field types. Let’s go through each of the field types in detail. FormType It is used to generate a form in Symfony framework. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypeTextType; use SymfonyComponentFormExtensionCoreTypeEmailType; use SymfonyComponentFormExtensionCoreTypeFormType; // … $builder = $this->createFormBuilder($studentinfo); $builder ->add(”title”, TextType::class); Here, $studentinfo is an entity of type Student. createFormBuilder is used to create a HTML form. add method is used to add input elements inside the form. title refers to student title property. TextType::class refers to html text field. Symfony provides classes for all html elements. TextType The TextType field represents the most basic input text field. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypeTextType; $builder->add(‘name’, TextType::class); Here, the name is mapped with an entity. TextareaType Renders a textarea HTML element. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypeTextareaType; $builder->add(”body”, TextareaType::class, array( ”attr” => array(”class” => ”tinymce”), )); EmailType The EmailType field is a text field that is rendered using the HTML5 email tag. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypeEmailType; $builder->add(”token”, EmailType::class, array( ”data” => ”abcdef”, )); PasswordType The PasswordType field renders an input password text box. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypePasswordType; $bulder->add(”password”, PasswordType::class); RangeType The RangeType field is a slider that is rendered using the HTML5 range tag. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypeRangeType; // … $builder->add(”name”, RangeType::class, array( ”attr” => array( ”min” => 100, ”max” => 200 ) )); PercentType The PercentType renders an input text field and specializes in handling percentage data. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypePercentType; // … $builder->add(”token”, PercentType::class, array( ”data” => ”abcdef”, )); DateType Renders a date format. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypeDateType; // … $builder->add(‘joined’, DateType::class, array( ”widget” => ”choice”, )); Here, Widget is the basic way to render a field. It performs the following function. choice − Renders three select inputs. The order of the selects is defined in the format option. text − Renders a three field input of type text (month, day, year). single_text − Renders a single input of type date. The user”s input is validated based on the format option. CheckboxType Creates a single input checkbox. This should always be used for a field that has a boolean value. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypeCheckboxType; // … $builder-<add(‘sports’, CheckboxType::class, array( ”label” =< ‘Are you interested in sports?’, ”required” =< false, )); RadioType Creates a single radio button. If the radio button is selected, the field will be set to the specified value. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypeRadioType; // … $builder->add(”token”, RadioType::class, array( ”data” => ”abcdef”, )); Note that, Radio buttons cannot be unchecked, the value only changes when another radio button with the same name gets checked. RepeatedType This is a special field “group”, that creates two identical fields whose values must match. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypeRepeatedType; use SymfonyComponentFormExtensionCoreTypePasswordType; // … $builder->add(”password”, RepeatedType::class, array( ”type” => PasswordType::class, ”invalid_message” => ”The password fields must match.”, ”options” => array(”attr” => array(”class” => ”password-field”)), ”required” => true, ”first_options” => array(”label” => ”Password”), ”second_options” => array(”label” => ”Repeat Password”), )); This is mostly used to check the user’s password or email. ButtonType A simple clickable button. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypeButtonType; // … $builder->add(”save”, ButtonType::class, array( ”attr” => array(”class” => ”save”), )); ResetType A button that resets all fields to its initial values. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypeResetType; // … $builder->add(”save”, ResetType::class, array( ”attr” => array(”class” => ”save”), )); ChoiceType A multi-purpose field is used to allow the user to “choose” one or more options. It can be rendered as a select tag, radio buttons, or checkboxes. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypeChoiceType; // … $builder->add(‘gender’, ChoiceType::class, array( ”choices” => array( ‘Male’ => true, ‘Female’ => false, ), )); SubmitType A submit button is used to submit form-data. Its syntax is as follows − use SymfonyComponentFormExtensionCoreTypeSubmitType; // … $builder->add(”save”, SubmitType::class, array( ”attr” => array(”class” => ”save”), )) Form Helper Function Form helper functions are twig functions used to create forms easily in templates. form_start Returns an HTML form tag that points to a valid action, route, or URL. Its syntax is as follows − {{ form_start(form, {”attr”: {”id”: ”form_person_edit”}}) }} form_end Closes the HTML form tag created using form_start. Its syntax is as follows − {{ form_end(form) }} textarea Returns a textarea tag, optionally wrapped with an inline rich-text JavaScript editor. checkbox Returns an XHTML compliant input tag with type=“checkbox”. Its syntax is as follows − echo checkbox_tag(”choice[]”, 1); echo checkbox_tag(”choice[]”, 2); echo checkbox_tag(”choice[]”, 3); echo checkbox_tag(”choice[]”, 4); input_password_tag Returns an XHTML compliant input tag with type = “password”. Its syntax is as follows − echo input_password_tag(”password”); echo input_password_tag(”password_confirm”); input_tag Returns an XHTML compliant input tag with type = “text”. Its syntax is as follows − echo input_tag(”name”); label Returns a label tag with the specified parameter. radiobutton Returns an XHTML compliant input tag with type = “radio”. Its syntax is as follows − echo ” Yes ”.radiobutton_tag(‘true’, 1); echo ” No ”.radiobutton_tag(‘false’, 0); reset_tag Returns an XHTML compliant input tag with type = “reset”. Its syntax is as follows − echo reset_tag(”Start Over”); select Returns a select tag populated with all the countries in the world. Its syntax is as follows − echo select_tag( ”url”, options_for_select($url_list), array(”onChange” => ”Javascript:this.form.submit();”)); submit Returns an XHTML compliant input tag with type = “submit”. Its syntax is as follows − echo submit_tag(”Update Record”); In the next section, we will learn how to create a form using form fields. Student Form Application Let’s create a simple Student details form using Symfony Form

Symfony – Validation

Symfony – Validation ”; Previous Next Validation is the most important aspect while designing an application. It validates the incoming data. This chapter explains about form validation in detail. Validation Constraints The validator is designed to validate objects against constraints. If you validate an object, simply map one or more constraints to its class and then pass it to the validator service. By default, when validating an object all constraints of the corresponding class will be checked to see whether or not they actually pass. Symfony supports the following notable validation constraints. NotBlank Validates that a property is not blank. Its syntax is as follows − namespace AppBundleEntity; use SymfonyComponentValidatorConstraints as Assert; class Student { /** * @AssertNotBlank() */ protected $studentName; } This NotBlank constraint ensures that studentName property should not blank. NotNull Validates that a value is not strictly equal to null. Its syntax is as follows − namespace AppBundleEntity; use SymfonyComponentValidatorConstraints as Assert; class Student { /** * @AssertNotNull() */ protected $studentName; } Email Validates that a value is a valid email address. Its syntax is as follows − namespace AppBundleEntity; use SymfonyComponentValidatorConstraints as Assert; class Student { /** * @AssertEmail( * message = “The email ”{{ value }}” is not a valid email.”, * checkMX = true * ) */ protected $email; } IsNull Validates that a value is exactly equal to null. Its syntax is as follows − namespace AppBundleEntity; use SymfonyComponentValidatorConstraints as Assert; class Student { /** * @AssertIsNull() */ protected $studentName; } Length Validates that a given string length is between some minimum and maximum value. Its syntax is as follows − namespace AppBundleEntity; use SymfonyComponentValidatorConstraints as Assert; class Student { /** * @AssertLength( * min = 5, * max = 25, * minMessage = “Your first name must be at least {{ limit }} characters long”, * maxMessage = “Your first name cannot be longer than {{ limit }} characters” * ) */ protected $studentName; } Range Validates that a given number is between some minimum and maximum number. Its syntax is as follows − namespace AppBundleEntity; use SymfonyComponentValidatorConstraints as Assert; class Student { /** * @AssertRange( * min = 40, * max = 100, * minMessage = “You must be at least {{ limit }} marks”, * maxMessage = “Your maximum {{ limit }} marks” * ) */ protected $marks; } Date Validates that a value is a valid date. It follows a valid YYYY-MM-DD format. Its syntax is as follows − namespace AppBundleEntity; use SymfonyComponentValidatorConstraints as Assert; class Student { /** * @AssertDate() */ protected $joinedAt; } Choice This constraint is used to ensure that the given value is one of a given set of valid choices. It can also be used to validate that each item in an array of items is one of those valid choices. Its syntax is as follows − namespace AppBundleEntity; use SymfonyComponentValidatorConstraints as Assert; class Student { /** * @AssertChoice(choices = {“male”, “female”}, message = “Choose a valid gender.”) */ protected $gender; } UserPassword This validates that an input value is equal to the current authenticated user”s password. This is useful in a form where users can change their password, but need to enter their old password for security. Its syntax is as follows − namespace AppBundleFormModel; use SymfonyComponentSecurityCoreValidatorConstraints as SecurityAssert; class ChangePassword { /** * @SecurityAssertUserPassword( * message = “Wrong value for your current password” * ) */ protected $oldPassword; } This constraint validates that the old password matches the user”s current password. Validation Example Let us write a simple application example to understand the validation concept. Step 1 − Create a validation application. Create a Symfony application, validationsample, using the following command. symfony new validationsample Step 2 − Create an entity named, FormValidation in file “FormValidation.php” under the “src/AppBundle/Entity/” directory. Add the following changes in the file. FormValidation.php <?php namespace AppBundleEntity; use SymfonyComponentValidatorConstraints as Assert; class FormValidation { /** * @AssertNotBlank() */ protected $name; /** * @AssertNotBlank() */ protected $id; protected $age; /** * @AssertNotBlank() */ protected $address; public $password; /** * @AssertEmail( * message = “The email ”{{ value }}” is not a valid email.”, * checkMX = true * ) */ protected $email; public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } public function getId() { return $this->id; } public function setId($id) { $this->id = $id; } public function getAge() { return $this->age; } public function setAge($age) { $this->age = $age; } public function getAddress() { return $this->address; } public function setAddress($address) { $this->address = $address; } public function getEmail() { return $this->email; } public function setEmail($email) { $this->email = $email; } } Step 3 − Create a validateAction method in StudentController. Move to the directory “src/AppBundle/Controller”, create “studentController.php” file, and add the following code in it. StudentController.php use AppBundleEntityFormValidation; /** * @Route(“/student/validate”) */ public function validateAction(Request $request) { $validate = new FormValidation(); $form = $this->createFormBuilder($validate) ->add(”name”, TextType::class) ->add(”id”, TextType::class) ->add(”age”, TextType::class) ->add(”address”, TextType::class) ->add(”email”, TextType::class) ->add(”save”, SubmitType::class, array(”label” => ”Submit”)) ->getForm(); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $validate = $form->getData(); return new Response(”Form is validated.”); } return $this->render(”student/validate.html.twig”, array( ”form” => $form->createView(), )); } Here, we have created the form using Form classes and then handled the form. If the form is submitted and is valid, a form validated message is shown. Otherwise, the default form is shown. Step 4 − Create a view for the above created action in StudentController. Move to the directory “app/Resources/views/student/”. Create “validate.html.twig” file and add the following code in it. {% extends ”base.html.twig” %} {% block stylesheets %} <style> #simpleform { width:600px; border:2px solid grey; padding:14px; } #simpleform label { font-size:14px; float:left; width:300px; text-align:right; display:block; } #simpleform span { font-size:11px; color:grey; width:100px; text-align:right; display:block; } #simpleform input { border:1px solid grey; font-family:verdana; font-size:14px; color:light blue; height:24px; width:250px; margin: 0 0 10px 10px; } #simpleform textarea { border:1px solid grey; font-family:verdana; font-size:14px; color:light blue; height:120px; width:250px; margin: 0 0 20px 10px; } #simpleform select { margin: 0 0 20px 10px; } #simpleform button { clear:both;

Symfony – Routing

Symfony – Routing ”; Previous Next Routing maps request URI to a specific controller”s method. In general, any URI has the following three parts − Hostname segment Path segment Query segment For example, in 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. Generally, routing checks the page segment against a set of constraints. If any constraint matches, then it returns a set of values. One of the main value is the controller. Annotations Annotation plays an important role in the configuration of Symfony application. Annotation simplifies the configuration by declaring the configuration in the coding itself. Annotation is nothing but providing meta information about class, methods, and properties. Routing uses annotation extensively. Even though routing can be done without annotation, annotation simplifies routing to a large extent. Following is a sample annotation. /** * @Route(“/student/home”) */ public function homeAction() { // … } Routing Concepts Consider the StudentController class created in “student” project. StudentController.php // src/AppBundle/Controller/StudentController.php namespace AppBundleController; use SymfonyBundleFrameworkBundleControllerController; use SensioBundleFrameworkExtraBundleConfigurationRoute; class StudentController extends Controller { /** * @Route(“/student/home”) */ public function homeAction() { // … } /** * @Route(“/student/about”) */ public function aboutAction() { } } Here, the routing performs two steps. If you go to /student/home, the first route is matched then homeAction() is executed. Otherwise, If you go to /student/about, the second route is matched and then aboutAction() is executed. Adding Wildcard Formats Consider, you have a paginated list of student records with URLs like /student/2 and /student/3 for page 2 and 3 correspondingly. Then, if you want to change the route”s path, you can use wildcard formats. Example // src/AppBundle/Controller/BlogController.php namespace AppBundleController; use SymfonyBundleFrameworkBundleControllerController; use SensioBundleFrameworkExtraBundleConfigurationRoute; class StudentController extends Controller { /** * @Route(“/student/{page}”, name = “student_about”, requirements = {“page”: “d+”}) */ public function aboutAction($page) { // … } } Here, the d+ is a regular expression that matches a digit of any length. Assign Placeholder You can assign a placeholder value in routing. It is defined as follows. // src/AppBundle/Controller/BlogController.php namespace AppBundleController; use SymfonyBundleFrameworkBundleControllerController; use SensioBundleFrameworkExtraBundleConfigurationRoute; 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 a value of 1. Redirecting to a Page 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”); } Generating URLs To generate a URL, consider a route name, student_name and wildcard name, student-names used in the path for that route. The complete listing for generating a 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’) ); } } StudentController Consider a simple example for routing in StudentController class as follows. StudentController.php <?php namespace AppBundleController; use SensioBundleFrameworkExtraBundleConfigurationRoute; use SymfonyComponentHttpFoundationResponse; use SymfonyBundleFrameworkBundleControllerController; class StudentController { /** * @Route(“/student/home”) */ public function homeAction() { $name = ”Student details application”; return new Response( ”<html><body>Project: ”.$name.”</body></html>” ); } } Now, request the url,”http://localhost:8000/student/home” and it produces the following result. Similarly, you can create another route for aboutAction() as well. Print Page Previous Next Advertisements ”;

Symfony – View Engine

Symfony – View Engine ”; Previous Next A View Layer is the presentation layer of the MVC application. It separates the application logic from the presentation logic. When a controller needs to generate HTML, CSS, or any other content then, it forwards the task to the templating engine. Templates Templates are basically text files used to generate any text-based documents such as HTML, XML, etc. It is used to save time and reduce errors. By default, templates can reside in two different locations − app/Resources/views/ − The application”s views directory can contain your application”s layouts and templates of the application bundle. It also overrides third party bundle templates. vendor/path/to/Bundle/Resources/views/ − Each third party bundle contains its templates in it”s “Resources/views/” directory. Twig Engine Symfony uses a powerful templating language called Twig. Twig allows you to write concise and readable templates in a very easy manner. Twig templates are simple and won”t process PHP tags. Twig performs whitespace control, sandboxing, and automatic HTML escaping. Syntax Twig contains three types of special syntax − {{ … }} − Prints a variable or the result of an expression to the template. {% … %} − A tag that controls the logic of the template. It is mainly used to execute a function. {# … #} − Comment syntax. It is used to add a single or multi-line comments. The twig base template is located at “app/Resources/views/base.html.twig”. Example Let’s go through a simple example using twig engine. StudentController.php <?php namespace AppBundleController; use SensioBundleFrameworkExtraBundleConfigurationRoute; use SymfonyComponentHttpFoundationResponse; use SymfonyBundleFrameworkBundleControllerController; class StudentController extends Controller { /** * @Route(“/student/home”) */ public function homeAction() { return $this->render(”student/home.html.twig”); } } Here, the render() method renders a template and puts that content into a Response object. Now move to the “views” directory and create a folder “student” and inside that folder create a file “home.html.twig”. Add the following changes in the file. home.html.twig //app/Resources/views/student/home.html.twig <h3>Student application!</h3> You can obtain the result by requesting the url “http://localhost:8000/student/home”. By default, Twig comes with a long list of tags, filters, and functions. Let’s go through one by one in detail. Tags Twig supports the following important tags − Do The do tag performs similar functions as regular expression with the exception that it doesn”t print anything. Its syntax is as follows − {% do 5 + 6 %} Include The include statement includes a template and returns the rendered content of that file into the current namespace. Its syntax is as follows − {% include ”template.html” %} Extends The extends tag can be used to extend a template from another one. Its syntax is as follows − {% extends “template.html” %} Block Block acts as a placeholder and replaces the contents. Block names consists of alphanumeric characters and underscores. For example, <title>{% block title %}{% endblock %}</title> Embed The embed tag performs a combination of both include and extends. It allows you to include another template”s contents. It also allows you to override any block defined inside the included template, such as when extending a template. Its syntax is as follows − {% embed “new_template.twig” %} {# These blocks are defined in “new_template.twig” #} {% block center %} Block content {% endblock %} {% endembed %} Filter Filter sections allow you to apply regular Twig filters on a block of template data. For example, {% filter upper %} symfony framework {% endfilter %} Here, the text will be changed to upper case. For For loop fetches each item in a sequence. For example, {% for x in 0..10 %} {{ x }} {% endfor %} If The if statement in Twig is similar to PHP. The expression evaluates to true or false. For example, {% if value == true %} <p>Simple If statement</p> {% endif %} Filters Twig contains filters. It is used to modify content before being rendered. Following are some of the notable filters. Length The length filter returns the length of a string. Its syntax is as follows − {% if name|length > 5 %} … {% endif %} Lower The lower filter converts a value to lowercase. For example, {{ ”SYMFONY”|lower }} It would produce the following result − symfony Similarly, you can try for upper case. Replace The replace filter formats a given string by replacing the placeholders. For example, {{ “tutorials point site %si% and %te%.”|replace({”%si%”: web, ”%te%”: “site”}) }} It will produce the following result − tutorials point website Title The title filter returns a titlecase version of the value. For example, {{ ”symfony framework ”|title }} It will produce the following result − Symfony Framework Sort The sort filter sorts an array. Its syntax is as follows − {% for user in names|sort %} … {% endfor %} Trim The trim filter trims whitespace (or other characters) from the beginning and the end of a string. For example, {{ ” Symfony! ”|trim }} It will produce the following result − Symfony! Functions Twig supports functions. It is used to obtain a particular result. Following are some of the important Twig functions. Attribute The attribute function can be used to access a “dynamic” attribute of a variable. Its syntax is as follows − {{ attribute(object, method) }} {{ attribute(object, method, arguments) }} {{ attribute(array, item) }} For example, {{ attribute(object, method) is defined ? ”Method exists” : ”Method does not exist” }} Constant Constant function returns the constant value for a specified string. For example, {{ constant(”Namespace\Classname::CONSTANT_NAME”) }} Cycle The cycle function cycles on an array of values. For example, {% set months = [‘Jan’, ‘Feb’, ‘Mar’] %} {% for x in 0..12 %} { cycle(months, x) }} {% endfor %} Date Converts an argument to a date to allow date comparison. For example, <p>Choose your location before {{ ”next Monday”|date(”M j, Y”) }}</p> It will produce the following result − Choose your location before May 15, 2017 The argument must be in one of PHP’s supported date and time formats. You can pass a timezone as the second argument. Dump The dump

Symfony – Expression

Symfony – Expression ”; Previous Next As we discussed earlier, expression language is one of the salient features of Symfony application. Symfony expression is mainly created to be used in a configuration environment. It enables a non-programmer to configure the web application with little effort. Let us create a simple application to test an expression. Step 1 − Create a project, expression-language-example. cd /path/to/dir mkdir expression-language-example cd expression-language-example composer require symfony/expression-language Step 2 − Create an expression object. use SymfonyComponentExpressionLanguageExpressionLanguage; $language = new ExpressionLanguage(); Step 3 − Test a simple expression. echo “Evaluated Value: ” . $language->evaluate(”10 + 12”) . “rn” ; echo “Compiled Code: ” . $language->compile(”130 % 34”) . “rn” ; Step 4 − Symfony expression is powerful such that it can intercept a PHP object and its property as well in the expression language. class Product { public $name; public $price; } $product = new Product(); $product->name = ”Cake”; $product->price = 10; echo “Product price is ” . $language ->evaluate(”product.price”, array(”product” => $product,)) . “rn”; echo “Is Product price higher than 5: ” . $language ->evaluate(”product.price > 5”, array(”product” => $product,)) . “rn”; Here, the expression product.price and product.price > 5 intercept $product object”s property price and evaluate the result. The complete coding is as follows. main.php <?php require __DIR__ . ”/vendor/autoload.php”; use SymfonyComponentExpressionLanguageExpressionLanguage; $language = new ExpressionLanguage(); echo “Evaluated Value: ” . $language->evaluate(”10 + 12”) . “rn” ; echo “Compiled Code: ” . $language->compile(”130 % 34”) . “rn” ; class Product { public $name; public $price; } $product = new Product(); $product->name = ”Cake”; $product->price = 10; echo “Product price is ” . $language ->evaluate(”product.price”, array(”product” => $product,)) . “rn”; echo “Is Product price higher than 5: ” . $language ->evaluate(”product.price > 5”, array(”product” => $product,)) . “rn”; ?> Result Evaluated Value: 22 Compiled Code: (130 % 34) Product price is 10 Is Product price higher than 5: 1 Print Page Previous Next Advertisements ”;

Symfony – Installation

Symfony – Installation ”; Previous Next This chapter explains how to install Symfony framework on your machine. Symfony framework installation is very simple and easy. You have two methods to create applications in Symfony framework. First method is using Symfony Installer, an application to create a project in Symfony framework. Second method is composer-based installation. Let’s go through each of the methods one by one in detail in the following sections. System Requirements Before moving to installation, you require the following system requirements. Web server (Any one of the following) WAMP (Windows) LAMP (Linux) XAMP (Multi-platform) MAMP (Macintosh) Nginx (Multi-platform) Microsoft IIS (Windows) PHP built-in development web server (Multi-platform) Operating System: Cross-platform Browser Support: IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera PHP Compatibility: PHP 5.4 or later. To get the maximum benefit, use the latest version. We will use PHP built-in development web server for this tutorial. Symfony Installer Symfony Installer is used to create web applications in Symfony framework. Now, let’s configure the Symfony installer using the following command. $ sudo mkdir -p /usr/local/bin $ sudo curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony $ sudo chmod a+x /usr/local/bin/symfony Now, you have installed Symfony installer on your machine. Create Your First Symfony Application Following syntax is used to create a Symfony application in the latest version. Syntax symfony new app_name Here, app_name is your new application name. You can specify any name you want. Example symfony new HelloWorld After executing the above command, you will see the following response. Downloading Symfony… 0 B/5.5 MiB ░░░░░░░░░░░ …………………………………………………………… …………………………………………………………… Preparing project… ✔ Symfony 3.2.7 was successfully installed. Now you can: * Change your current directory to /Users/../workspace/firstapp * Configure your application in app/config/parameters.yml file. * Run your application: 1. Execute the php bin/console server:run command. 2. Browse to the http://localhost:8000 URL. * Read the documentation at http://symfony.com/doc This command creates a new directory called “firstapp/“ that contains an empty project of Symfony framework latest version. Install Specific Version If you need to install a specific Symfony version, use the following command. symfony new app_name 2.8 symfony new app_name 3.1 Composer-based Installation You can create Symfony applications using the Composer. Hopefully, you have installed the composer on your machine. If the composer is not installed, download and install it. The following command is used to create a project using the composer. $ composer create-project symfony/framework-standard-edition app_name If you need to specify a specific version, you can specify in the above command. Running the Application Move to the project directory and run the application using the following command. cd HelloWorld php bin/console server:run After executing the above command, open your browser and request the url http://localhost:8000/. It produces the following result. Result Print Page Previous Next Advertisements ”;