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 ”;
Category: symfony
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 ”;
Symfony – CMF Edition
Symfony – CMF Edition ”; Previous Next Content management system is one of the largest market in the web application scenario. There are a lot of frameworks available for content management system, in virtually all languages under the sun. Most of the frameworks are easy to work as an end customer but very hard to work with as a developer and vice-versa. Symfony provides a simple and easy framework for a developer to start with. It has all the basic features expected by an end customer as well. In short, it is the responsibility of the developer to provide a great experience for the end customer. Let us see how to install a CMS application template using Symfony CMF edition. Step 1 − Download Symfony CMF sandbox using the following command. composer create-project symfony-cmf/sandbox cmf-sandbox This will download the Symfony CMF. 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 − Create demo database using the console application as follows. php app/console doctrine:database:create Step 4 − Load the demo data into the database using the following command. php app/console doctrine:phpcr:init:dbal –force php app/console doctrine:phpcr:repository:init php app/console doctrine:phpcr:fixtures:load -n Step 5 − Now, run the application using the following command. php app/console server:run Step 6 − Finally, open the application in the browser using http://localhost:8000/. It will produce the following output − Print Page Previous Next Advertisements ”;
Symfony – Internationalization ”; Previous Next Internationalization (i18n) and Localization (l10n) help to increase the customer coverage of a web application. Symfony provides an excellent Translation component for this purpose. Let us learn how to use the Translation component in this chapter. Enable Translation By default, Symfony web framework disables Translation component. To enable it, add the translator section in the configuration file, app/config/config.yml. framework: translator: { fallbacks: [en] } Translation File Translation component translates the text using the translation resource file. The resource file may be written in PHP, XML, and YAML. The default location of the resource file is app/Resources/translations. It needs one resource file per language. Let us write a resource file, messages.fr.yml for French language. I love Symfony: J”aime Symfony I love %name%: J”aime %name% The left side text is in English and the right side text is in French. The second line shows the use of a placeholder. The placeholder information can be added dynamically while using translation. Usage By default, the default locale of the user”s system will be set by the Symfony web framework. If the default locale is not configured in the web application, it will fallback to English. The locale can be set in the URL of the web page as well. http://www.somedomain.com/en/index http://www.somedomain.com/fr/index Let us use URL-based locale in our example to easily understand the translation concept. Create a new function, translationSample with route /{_locale}/translation/sample in DefaultController (src/AppBundle/Controller/DefaultController.php). {_locale} is a special keyword in Symfony to specify the default locale. /** * @Route(“/{_locale}/translation/sample”, name=”translation_sample”) */ public function translationSample() { $translated = $this->get(”translator”)->trans(”I love Symfony”); return new Response($translated); } Here, we have used translation method, trans, which translates the content to the current locale. In this case, the current locale is the first part of the URL. Now, run the application and load the page, http://localhost:8000/en/translation/sample in the browser. The result will be “I love Symfony” in English language. Now, load the page http://localhost:8000/fr/translation/sample in the browser. Now, the text will be translated to French as follows. Similarly, twig template has {% trans %} block to enable translation feature in views as well. To check it, add a new function, translationTwigSample and the corresponding view at app/Resources/views/translate/index.html.twig. /** * @Route(“/{_locale}/translation/twigsample”, name=”translation_twig_sample”) */ public function translationTwigSample() { return $this->render(”translate/index.html.twig”); } View {% extends ”base.html.twig” %} {% block body %} {% trans with {”%name%”: ”Symfony”} from “app” into “fr” %}I love %name% {% endtrans %} {% endblock %} Here, the trans block specifies the placeholder as well. The page result is as follows. Print Page Previous Next Advertisements ”;
Symfony – Controllers
Symfony – Controllers ”; Previous Next Controller is responsible for handling each request that comes into Symfony application. Controller reads an information from the request. Then, creates and returns a response object to the client. According to Symfony, DefaultController class is located at “src/AppBundle/Controller”. It is defined as follows. DefaultController.php <?php namespace AppBundleController; use SymfonyBundleFrameworkBundleControllerController; use SymfonyComponentHttpFoundationResponse; class DefaultController extends Controller { } Here, the HttpFoundation component defines an object-oriented layer for the HTTP specification, and the FrameworkBundle contains most of the “base” framework functionality. Request Object The Request class is an object-oriented representation of the HTTP request message. Creating a Request Object Request can be created using createFromGlobals() method. use SymfonyComponentHttpFoundationRequest; $request = Request::createFromGlobals(); You can simulate a request using Globals. Instead of creating a request based on the PHP globals, 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 a Request Object You can override the PHP global variables using the overrideGlobals() method. It is defined as follows. $request->overrideGlobals(); Accessing a Request Object Request of a web page can be accessed in a controller (action method) using getRequest() method of the base controller. $request = $this->getRequest(); Identifying a Request Object If you want to identify a request in your application, “PathInfo” method will return the unique identity of the request url. It is defined as follows. $request->getPathInfo(); Response Object The only requirement for a controller is to return a Response object. A Response object holds all the information from a given request and sends it back to the client. Following is a simple example. Example use SymfonyComponentHttpFoundationResponse; $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 contains three arguments − The response content The status code An array of HTTP headers Following is the basic syntax. use SymfonyComponentHttpFoundationResponse; $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’); Similarly, you can pass other arguments as well. Sending Response You can send a 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 SymfonyComponentHttpFoundationRedirectResponse; $response = new RedirectResponse(”http://tutorialspoint.com/”); FrontController A single PHP file that handles every request coming into your application. FrontController executes the routing of different URLs to internally different parts of the application. Following is the basic syntax for FrontController. use SymfonyComponentHttpFoundationRequest; use SymfonyComponentHttpFoundationResponse; $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 searches an array for a specific value. Print Page Previous Next Advertisements ”;
Symfony – Logging
Symfony – Logging ”; Previous Next Logging is very important for a web application. Web applications are used by hundreds to thousands of users at a time. To get sneak preview of happenings around a web application, Logging should be enabled. Without logging, the developer will not be able to find the status of the application. Let us consider that an end customer reports an issue or a project stackholder reports performance issue, then the first tool for the developer is Logging. By checking the log information, one can get some idea about the possible reason of the issue. Symfony provides an excellent logging feature by integrating Monolog logging framework. Monolog is a de-facto standard for logging in PHP environment. Logging is enabled in every Symfony web application and it is provided as a Service. Simply get the logger object using base controller as follows. $logger = $this->get(”logger”); Once the logger object is fetched, we can log information, warning, and error using it. $logger->info(”Hi, It is just a information. Nothing to worry.”); $logger->warn(”Hi, Something is fishy. Please check it.”); $logger->error(”Hi, Some error occured. Check it now.”); $logger->critical(”Hi, Something catastrophic occured. Hurry up!”); Symfony web application configuration file app/config/config.yml has a separate section for the logger framework. It can be used to update the working of the logger framework. Print Page Previous Next Advertisements ”;
Symfony – Email Management
Symfony – Email Management ”; Previous Next Email functionality is the most requested feature in a web framework. Even a simple application will have a contact form and the details will be sent to the system administration through email. Symfony integrates SwiftMailer, the best PHP email module available in the market. SwiftMailer is an excellent email library providing an option to send email using old-school sendmail to the latest cloud-based mailer application. Let us understand the concept of mailing in Symfony by sending a simple email. Before writing the mailer functionality, set the mailer configuration details in app/config/parameters.yml. Then, create a new function, MailerSample in DefaultController and add the following code. /** * @Route(“/mailsample/send”, name=”mail_sample_send”) */ public function MailerSample() { $message = Swift_Message::newInstance() ->setSubject(”Hello Email”) ->setFrom(”[email protected]”) ->setTo(”[email protected]”) ->setBody( $this->renderView(”Emails/sample.html.twig”), ”text/html” ); $this->get(”mailer”)->send($message); return new Response(“Mail send”); } Here, we have simply created a message using SwiftMailer component and rendered the body of the message using Twig template. Then, we fetched the mailer component from the controller”s get method with the key ‘mailer’. Finally, we sent the message using send method and printed the Mail send message. Now, run the page, http://localhost:8000/mailsample/send and the result would be as follows. Print Page Previous Next Advertisements ”;
Symfony – Doctrine ORM
Symfony – Doctrine ORM ”; Previous Next In Symfony web framework, model plays an important role. They are the business entities. They are either provided by customers or fetched from back-end database, manipulated according to business rules and persisted back into the database. They are the data presented by Views. Let us learn about models and how they interact with back-end system in this chapter. Database Model We need to map our models to the back-end relational database items to safely and efficiently fetch and persist the models. This mapping can be done with an Object Relational Mapping (ORM) tool. Symfony provides a separate bundle, DoctrineBundle, which integrates Symfony with third party PHP database ORM tool, Doctrine. Doctrine ORM By default, Symfony framework doesn”t provide any component to work with databases. But, it integrates tightly with Doctrine ORM. Doctrine contains several PHP libraries used for database storage and object mapping. Following example will help you understand how Doctrine works, how to configure a database and how to save and retrieve the data. Doctrine ORM Example In this example, we will first configure the database and create a Student object, then perform some operations in it. To do this we need to adhere to the following steps. Step 1: Create a Symfony Application Create a Symfony application, dbsample using the following command. symfony new dbsample Step 2: Configure a Database Generally, the database information is configured in “app/config/parameters.yml” file. Open the file and add the following changes. parameter.yml parameters: database_host: 127.0.0.1 database_port: null database_name: studentsdb database_user: <user_name> database_password: <password> mailer_transport: smtp mailer_host: 127.0.0.1 mailer_user: null mailer_password: null secret: 037ab82c601c10402408b2b190d5530d602b5809 doctrine: dbal: driver: pdo_mysql host: ”%database_host%” dbname: ”%database_name%” user: ”%database_user%” password: ”%database_password%” charset: utf8mb4 Now, Doctrine ORM can connect to the database. Step 3: Create a Database Issue the following command to generate “studentsdb” database. This step is used to bind the database in Doctrine ORM. php bin/console doctrine:database:create After executing the command, it automatically generates an empty “studentsdb” database. You can see the following response on your screen. Created database `studentsdb` for connection named default Step 4: Map Information Mapping information is nothing but “metadata”. It is a collection of rules that informs Doctrine ORM exactly how the Student class and its properties are mapped to a specific database table. Well, this metadata can be specified in a number of different formats, including YAML, XML or you can directly pass Student class using annotations. It is defined as follows. Student.php Add the following changes in the file. <?php namespace AppBundleEntity; use DoctrineORMMapping as ORM; /** * @ORMEntity * @ORMTable(name = “students”) */ class Student { /** * @ORMColumn(type = “integer”) * @ORMId * @ORMGeneratedValue(strategy = “AUTO”) */ private $id; /** * @ORMColumn(type = “string”, length = 50) */ private $name; /** * @ORMColumn(type = “text”) */ private $address; } Here, the table name is optional. If the table name is not specified, then it will be determined automatically based on the name of the entity class. Step 5: Bind an Entity Doctrine creates simple entity classes for you. It helps you build any entity. Issue the following command to generate an entity. php bin/console doctrine:generate:entities AppBundle/Entity/Student Then you will see the following result and the entity will be updated. Generating entity “AppBundleEntityStudent” > backing up Student.php to Student.php~ > generating AppBundleEntityStudent Student.php <?php namespace AppBundleEntity; use DoctrineORMMapping as ORM; /** * @ORMEntity * @ORMTable(name=”students”) */ class Student { /** * @ORMColumn(type=”integer”) * @ORMId * @ORMGeneratedValue(strategy=”AUTO”) */ private $id; /** * @ORMColumn(type = “string”, length = 50) */ private $name; /** * @ORMColumn(type = “text”) */ private $address; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return Student */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set address * * @param string $address * * @return Student */ public function setAddress($address) { $this->address = $address; return $this; } /** * Get address * * @return string */ public function getAddress() { return $this->address; } } Step 6: Map Validation After creating entities, you should validate the mappings using the following command. php bin/console doctrine:schema:validate It will produce the following result − [Mapping] OK – The mapping files are correct. [Database] FAIL – The database schema is not in sync with the current mapping file Since we have not created the students table, the entity is out of sync. Let us create the students table using the Symfony command in the next step. Step 7: Create a Schema Doctrine can automatically create all the database tables needed for Student entity. This can be done using the following command. php bin/console doctrine:schema:update –force After executing the command, you can see the following response. Updating database schema… Database schema updated successfully! “1” query was executed This command compares what your database should look like with how it actually looks, and executes the SQL statements needed to update the database schema to where it should be. Now, again validate the schema using the following command. php bin/console doctrine:schema:validate It will produce the following result − [Mapping] OK – The mapping files are correct. [Database] OK – The database schema is in sync with the mapping files Step 8: Getter and setter As seen in the Bind an Entity section, the following command generates all the getters and setters for the Student class. $ php bin/console doctrine:generate:entities AppBundle/Entity/Student Step 9: Persist Objects to the Database Now, we have mapped the Student entity to its corresponding Student table. We should now be able to persist Student objects to the database. Add the following method to the StudentController of the bundle. StudentController.php <?php namespace AppBundleController; use SensioBundleFrameworkExtraBundleConfigurationRoute; use SymfonyBundleFrameworkBundleControllerController; use SymfonyComponentHttpFoundationResponse; use AppBundleEntityStudent; class StudentController extends Controller { /** * @Route(“/student/add”) */ public function addAction() { $stud = new Student(); $stud->setName(”Adam”); $stud->setAddress(”12 north street”); $doct
Symfony – Events and EventListener ”; Previous Next Symfony provides event-based programming through its EventDispatcher component. Any enterprise application needs event-based programming to create a highly customizable application. Events is one of the main tools for the objects to interact with each other. Without events, an object does not interact efficiently. The process of event based programming can be summarized as – An object, called Event source asks the central dispatcher object to register an event, say user.registered. One or more objects, called listener asks the central dispatcher object that it wants to listen to a specific event, say user.registered. At some point of time, the Event source object asks the central dispatcher object to dispatch the event, say user.registered along with an Event object with the necessary information. The central dispatcher informs all listener objects about the event, say user.registered and its Event* object. In event-based programming, we have four types of objects: Event Source, Event Listener, Even Dispatcher, and the Event itself. Let us write a simple application to understand the concept. Step 1 − Create a project, event-dispatcher-example. cd /path/to/dir mkdir event-dispatcher-example cd event-dispatcher-example composer require symfony/event-dispatcher Step 2 − Create a class, .User. class User { public $name; public $age; } $user = new User(); $user->name = “Jon”; $user->age = 25 Step 3 − Create an event, UserRegisteredEvent. use SymfonyComponentEventDispatcherEvent; class UserRegisteredEvent extends Event { const NAME = ”user.registered”; protected $user; public function __construct(User $user) { $this-<user = $user; } public function getUser() { return $this-<user; } } $event = new UserRegisteredEvent($user); Here, UserRegisteredEvent has access to User object. The name of the event is user.registered. Step 4 − Create a listener, UserListener. class UserListener { public function onUserRegistrationAction(Event $event) { $user = $event->getUser(); echo $user->name . “rn”; echo $user->age . “rn”; } } $listener = new UserListener(); Step 5 − Create an event dispatcher object. use SymfonyComponentEventDispatcherEventDispatcher; $dispatcher = new EventDispatcher(); Step 6 − Connect listener and event using dispatcher object and its method, addListener. $dispatcher ->addListener( UserRegisteredEvent::NAME, array($listener, ”onUserRegistrationAction”)); We can also add an anonymous function as event listener as shown in the following code. $dispatcher ->addListener( UserRegisteredEvent::NAME, function(Event $event) { $user = $event->getUser(); echo $user->name . “rn”; }); Step 7 − Finally, fire / dispatch the event using event dispatcher”s method, dispatch. $dispatcher->dispatch(UserRegisteredEvent::NAME, $event); The complete code listing is as follows. main.php <?php require __DIR__ . ”/vendor/autoload.php”; use SymfonyComponentEventDispatcherEventDispatcher; use SymfonyComponentEventDispatcherEvent; class User { public $name; public $age; } class UserRegisteredEvent extends Event { const NAME = ”user.registered”; protected $user; public function __construct(User $user) { $this->user = $user; } public function getUser() { return $this->user; } } class UserListener { public function onUserRegistrationAction(Event $event) { $user = $event->getUser(); echo $user->name . “rn”; echo $user->age . “rn”; } } $user = new User(); $user->name = “Jon”; $user->age = 25; $event = new UserRegisteredEvent($user); $listener = new UserListener(); $dispatcher = new EventDispatcher(); $dispatcher ->addListener( UserRegisteredEvent::NAME, function(Event $event) { $user = $event->getUser(); echo $user->name . “rn”; }); $dispatcher ->addListener( UserRegisteredEvent::NAME, array($listener, ”onUserRegistrationAction”)); $dispatcher->dispatch(UserRegisteredEvent::NAME, $event); ?> Result Jon Jon 25 Symfony web framework has a lot of events and one can register listener for those events and program it accordingly. One of the sample event is kernel.exception and the corresponding event is GetResponseForExceptionEvent, which holds the response object (the output of a web request). This is used to catch the exception and modify the response with generic error information instead of showing runtime error to the users. Print Page Previous Next Advertisements ”;
Symfony – Service Container
Symfony – Service Container ”; Previous Next In any application, objects tend to increase as the application grows. As objects increase, the dependency between the objects also increases. Object dependency needs to be handled properly for a successful application. As discussed in the Components chapter, Symfony provides an easy and efficient component, DependencyInjection to handle object dependency. A service container is a container of objects with properly resolved dependency between them. Let us learn how to use DependencyInjection component in this chapter. Let us create a Greeter class. The purpose of the Greeter class is to greet the user as shown in the following example. $greeter = new Greeter(”Hi”); $greeter->greet(”Jon”); // print “Hi, Jon” The complete code of the Greeter class is as follows. class Greeter { private $greetingText; public function __construct($greetingText) { $this->greetingText = $greetingText; } public function greet($name) { echo $this->greetingText . “, ” . $name . “rn”; } } Now, let us add Greeter class to the service container. Symfony provides ContainerBuilder to create a new container. Once the container is created, Greeter class can be registered into it using the container”s register method. use SymfonyComponentDependencyInjectionContainerBuilder; $container = new ContainerBuilder(); $container ->register(”greeter”, ”Greeter”) ->addArgument(”Hi”); Here, we have used static argument to specify the greeting text, Hi. Symfony provides a dynamic setting of parameter as well. To use a dynamic parameter, we need to choose a name and specify it between % and the parameter can be set using container”s setParameter method. $container = new ContainerBuilder(); $container ->register(”greeter”, ”Greeter”) ->addArgument(”%greeter.text%”); $container->setParameter(”greeter.text”, ”Hi”); We have registered a Greeter class with proper setting. Now, we can ask the container to provide a properly configured Greeter object using the container get method. $greeter = $container->get(”greeter”); $greeter->greet(”Jon”); // prints “Hi, Jon” We have successfully registered a class, Greeter into container, fetched it from the container and used it. Now, let us create another class User, which use Greeter class and see how to register it. class User { private $greeter; public $name; public $age; public function setGreeter(Greeter $greeter) { $this->greeter = $greeter; } public function greet() { $this->greeter->greet($this->name); } } The User class gets the Greeter class using one of its setter method, setGreeter. For this scenario, Symfony provides a method, addMethodCall and a class, Reference to refer another class as shown in the following code. use SymfonyComponentDependencyInjectionReference; $container ->register(”user”, ”User”) ->addMethodCall(”setGreeter”, array(new Reference(”greeter”))); Finally, we have registered two classes, Greeter and User having a strong relation between them. Now, we can safely fetch the User object with properly configured Greeter class from the container as shown in the following code. $container->setParameter(”greeter.text”, ”Hi”); $user = $container->get(”user”); $user->name = “Jon”; $user->age = 20; $user->greet(); // Prints “Hi, Jon” We have seen how to configure an object in a container using PHP itself. Symfony provides other mechanisms as well. They are XML and YAML configuration files. Let us see how to configure a container using YAML. For this, install symfony/config and symfony/yaml components along with symfony/dependency-injection components. cd /path/to/dir mkdir dependency-injection-example cd dependency-injection-example composer require symfony/dependency-injection composer require symfony/config composer require symfony/yaml YAML configuration will be written in a separate file, services.yml. YAML configuration consists of two sections, parameters and services. Parameters section defines all required parameters. Services section defines all objects. Services section is further divided into multiple sections namely, class, arguments, and calls. Class specifies the actual class. Arguments specifies the constructor”s arguments. Finally, calls specify the setter methods. Another class can be referred using @ symbol, @greeter. parameters: greeter.text: ”Hello” services: greeter: class: Greeter arguments: [”%greeter.text%”] user: class: User calls: – [setGreeter, [”@greeter”]] Now, services.yml can be loaded and configured using FileLoader and YamlFileLoader as shown in the following code. use SymfonyComponentConfigFileLocator; use SymfonyComponentDependencyInjectionLoaderYamlFileLoader; $yamlContainer = new ContainerBuilder(); $loader = new YamlFileLoader($yamlContainer, new FileLocator(__DIR__)); $loader->load(”services.yml”); $yamlUser = $yamlContainer->get(”user”); $yamlUser->name = “Jon”; $yamlUser->age = 25; $yamlUser->greet(); The complete code listing is as follows. main.php <?php require __DIR__ . ”/vendor/autoload.php”; use SymfonyComponentDependencyInjectionContainerBuilder; use SymfonyComponentConfigFileLocator; use SymfonyComponentDependencyInjectionLoaderYamlFileLoader; use SymfonyComponentDependencyInjectionReference; class Greeter { private $greetingText; public function __construct($greetingText) { $this->greetingText = $greetingText; } public function greet($name) { echo $this->greetingText . “, ” . $name . “rn”; } } class User { private $greeter; public $name; public $age; public function setGreeter(Greeter $greeter) { $this->greeter = $greeter; } public function greet() { $this->greeter->greet($this->name); } } $container = new ContainerBuilder(); $container ->register(”greeter”, ”Greeter”) ->addArgument(”%greeter.text%”); $container ->register(”user”, ”User”) ->addMethodCall(”setGreeter”, array(new Reference(”greeter”))); $container->setParameter(”greeter.text”, ”Hi”); $greeter = $container->get(”greeter”); $greeter->greet(”Jon”); $user = $container->get(”user”); $user->name = “Jon”; $user->age = 20; $user->greet(); $yamlContainer = new ContainerBuilder(); $loader = new YamlFileLoader($yamlContainer, new FileLocator(__DIR__)); $loader->load(”services.yml”); $yamlHello = $yamlContainer->get(”greeter”); $yamlHello->greet(”Jon”); $yamlUser = $yamlContainer->get(”user”); $yamlUser->name = “Jon”; $yamlUser->age = 25; $yamlUser->greet(); ?> services.yml parameters: greeter.text: ”Hello” services: greeter: class: Greeter arguments: [”%greeter.text%”] user: class: User calls: – [setGreeter, [”@greeter”]] Symfony web framework uses the dependency injection component extensively. All the components are bound by the centralized service container. Symfony web framework exposes the container in all its Controller through container property. We can get all object registered in it, say logger, mailer, etc., through it. $logger = $this->container->get(”logger”); $logger->info(”Hi”); To find the object registered in the container, use the following command. cd /path/to/app php bin/console debug:container There are around 200+ objects in the hello web app created in the installation chapter. Print Page Previous Next Advertisements ”;