<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Luka Gado on Medium]]></title>
        <description><![CDATA[Stories by Luka Gado on Medium]]></description>
        <link>https://medium.com/@lukagado?source=rss-98e8c33750dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6Bi2NMHgEYYrqk2G</url>
            <title>Stories by Luka Gado on Medium</title>
            <link>https://medium.com/@lukagado?source=rss-98e8c33750dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 02:54:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lukagado/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Symfony 5 — The REST, the CRUD and the Swag]]></title>
            <link>https://medium.com/q-software/symfony-5-the-rest-the-crud-and-the-swag-7430cb84cd5?source=rss-98e8c33750dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7430cb84cd5</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[q-software]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[q-engineering]]></category>
            <dc:creator><![CDATA[Luka Gado]]></dc:creator>
            <pubDate>Thu, 28 Nov 2019 09:47:35 GMT</pubDate>
            <atom:updated>2019-11-28T10:15:02.792Z</atom:updated>
            <content:encoded><![CDATA[<h3>Symfony 5 — The REST, the CRUD and the Swag</h3><p>In this tutorial I will show you how to install fresh Symfony 5 project and how to make simple CRUD in REST based architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*wkNYF-hoPtar-2OQYM0lWw.png" /></figure><p>REST or representational stateless transfer is an architectural style for APIs wrapped around the user and the resources accessible to them.</p><p><strong>Stateless</strong> — meaning the server doesn’t remember anything about the user who uses the API.</p><p>CRUD or Create, Read, Update and Delete are four basic functionalities of an API. Each of them is represented by a HTTP method:</p><ul><li><strong>POST</strong> — Create (insert data)</li><li><strong>GET</strong> — Read (retrieve data)</li><li><strong>PUT</strong> <strong>/PATCH</strong>— Update (modify data)</li><li><strong>DELETE</strong> — Delete (delete data)</li></ul><p>I will explain the difference between PUT and PATCH later in the article, don’t want to spoil the article right at the beginning.</p><h3>Requirements</h3><ul><li>Symfony 5.0</li><li>Faker</li></ul><h3>Getting Started</h3><p>First of all we need the newest Symfony 5.0 skeleton released this month:</p><pre><em>symfony new project-name</em></pre><p>or with the PHP dependency manager Composer:</p><pre><em>composer create-project symfony/website-skeleton project-name</em></pre><p>Now you can run the command just to check out everything went fine while downloading:</p><pre>symfony server:start</pre><p>This command will give you a link to your Symfony index page something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dZxTMmkX2-_E7sefSepBw.png" /></figure><h3>Database and Entity</h3><p>To make our first Entity that we are going to use in this tutorial with our CRUD functionalities we need to require these two commands:</p><pre>composer require symfony/orm-pack<br>composer require --dev symfony/maker-bundle</pre><p>We need to modify <em>DATABASE_URL</em> parameter in .env file. Insert your username and password you have been provided with when installing MySQL server:</p><pre>DATABASE_URL=mysql://username:password@127.0.0.1:3306/database_name?serverVersion=8.0</pre><p>Now we are ready to execute something very helpful these bundles are offering us to simply trough terminal generate the entity and the repository and that is:</p><pre>bin/console make:entity</pre><p>I made a simple Customer entity with properties:</p><ul><li>firstName - string</li><li>lastName - string</li><li>email - string</li><li>phoneNumber - string</li></ul><p>You can see our two new files - <em>Customer.php</em> in Entity folder and <em>CustomerRepository.php </em>in Repository folder. At the top of <em>Customer</em> entity class you can see the annotation for repository class - that means both class interact with each other and Doctrine gives us an instance of <em>CustomerRepository</em> class when <em>Customer</em> entity is being used. If you check out <em>CustomerRepository</em> class you can see we have two commented examples of functions fetching different data by field. So, if you want to make custom methods for searching, updating, deleting etc … for your entity, you write it in the Repository class.</p><p>We will slightly adjust our <em>Customer </em>file in our Entity folder. Above the email variable, add “unique=true”. This means our database won’t accept two of the same emails if they are added to the database:</p><pre><em>/**<br> * </em><strong><em>@ORM\Column</em></strong><em>(type=&quot;string&quot;, length=255, unique=true)<br> */<br></em>private $email;</pre><p>Add one more function at the end of the file called <em>toArray. </em>Function is converting our object to array so we can display it in our JsonResponse:</p><pre>public function toArray()<br>{<br>    return [<br>        &#39;id&#39; =&gt; $this-&gt;getId(),<br>        &#39;firstName&#39; =&gt; $this-&gt;getFirstName(),<br>        &#39;lastName&#39; =&gt; $this-&gt;getLastName(),<br>        &#39;email&#39; =&gt; $this-&gt;getEmail(),<br>        &#39;phoneNumber&#39; =&gt; $this-&gt;getPhoneNumber()<br>    ];<br>}</pre><p>If you are happy with your entity and its functions, we can generate and run our first migration version:</p><pre>bin/console make:migration<br>bin/console doctrine:migrations:migrate</pre><p>And now your database should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*TQ762H9vFdhUiC8_hW_h5Q.png" /></figure><p>If you’ll ever want to expand your Entities but already have a migration file, no worries. Whenever you make a change to your entity simply run the two commands above the picture and you are good.</p><h3>Mock It Up!</h3><p>For this tutorial we need some data so we can play around with our CRUD. Enter Faker! With Faker you can add a variety of random information to your database (phone number, emails, first names, last names etc …). For using fixtures in Symfony run this command and it will generate DataFixtures folder:</p><pre>composer require --dev orm-fixtures</pre><p>Inside you will see <em>AppFixtures.php</em> file that extends Fixtures. We will simply add Faker and a small For loop for adding data to our database like this:</p><pre>class AppFixtures extends Fixture<br>{<br>    public function load(ObjectManager $manager)<br>    {<br>        $faker = Factory::<em>create</em>();<br><br>        for ($i = 0; $i &lt; 50; $i++) {<br>            $customer = new Customer();<br>            $customer-&gt;setFirstName($faker-&gt;firstName);<br>            $customer-&gt;setLastName($faker-&gt;lastName);<br>            $customer-&gt;setEmail($faker-&gt;email);<br>            $customer-&gt;setPhoneNumber($faker-&gt;phoneNumber);<br>            $manager-&gt;persist($customer);<br>        }<br><br>        $manager-&gt;flush();<br>    }<br>}</pre><p>This will then populate our database with 50 records of random customers:</p><pre>bin/console doctrine:fixtures:load</pre><h3>Our first (and only) controller</h3><h3>Creating</h3><p>Create a <em>CustomerController</em> class in Controller folder and add annotations to your project so we can adjust our routes:</p><pre>composer require annotations</pre><p>In your <em>CustomerController</em> we will make a function called <em>addCustomer</em> which is going to do exactly what it’s called.</p><pre>class CustomerController<br>{<br>    private $customerRepository;<br><br>    public function __construct(CustomerRepository $customerRepository)<br>    {<br>        $this-&gt;customerRepository = $customerRepository;<br>    }<br><br>    <em>/**<br>     * </em><strong><em>@Route</em></strong><em>(&quot;/customers/&quot;, name=&quot;add_customer&quot;, methods={&quot;POST&quot;})<br>     */<br>    </em>public function add(Request $request): JsonResponse<br>    {<br>        $data = json_decode($request-&gt;getContent(), true);<br><br>        $firstName = $data[&#39;firstName&#39;];<br>        $lastName = $data[&#39;lastName&#39;];<br>        $email = $data[&#39;email&#39;];<br>        $phoneNumber = $data[&#39;phoneNumber&#39;];<br><br>        if (empty($firstName) || empty($lastName) || empty($email) || empty($phoneNumber)) {<br>            throw new NotFoundHttpException(&#39;Expecting mandatory parameters!&#39;);<br>        }<br><br>        $this-&gt;customerRepository-&gt;saveCustomer($firstName, $lastName, $email, $phoneNumber);<br><br>        return new JsonResponse([&#39;status&#39; =&gt; &#39;Customer created!&#39;], Response::<em>HTTP_CREATED</em>);<br>    }<br>}</pre><p>We have a constructor where we injected <em>CustomerRepository</em> class which we are going to update with a function for saving the data to the database. From the <em>Request</em> we will get our data and <em>json_decode</em> function makes it into array so we can add them to our corresponding variables. Before we pass variables to our <em>saveCustomer</em> function we check if they are empty since all our fields in database are not nullable.</p><p>In <em>CustomerRepository</em> modify your code like this:</p><pre>class CustomerRepository extends ServiceEntityRepository<br>{<br>    private $manager;<br><br>    public function __construct<br>    (<br>        ManagerRegistry $registry,<br>        EntityManagerInterface $manager<br>    )<br>    {<br>        parent::<em>__construct</em>($registry, Customer::class);<br>        $this-&gt;manager = $manager;<br>    }<br><br>    public function saveCustomer($firstName, $lastName, $email, $phoneNumber)<br>    {<br>        $newCustomer = new Customer();<br><br>        $newCustomer<br>            -&gt;setFirstName($firstName)<br>            -&gt;setLastName($lastName)<br>            -&gt;setEmail($email)<br>            -&gt;setPhoneNumber($phoneNumber);<br><br>        $this-&gt;manager-&gt;persist($newCustomer);<br>        $this-&gt;manager-&gt;flush();<br>    }<br>}</pre><p>We passed our variables from the controller to our <em>saveCustomer</em> function where we set them and, in the end, store them to our database.</p><p>To try this out, download Postman from the link below:</p><p><a href="https://www.getpostman.com/">Postman | The Collaboration Platform for API Development</a></p><p>Your POST request should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_r5IVHm1t_Fm9TD3fR6OLw.png" /></figure><p>And in the end, if everything is okay after your pressed “Send”, the response should be just as the one below the request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*NNYJGU-cN6jKxD4X8QQR5g.png" /></figure><p>Congratulations! You have have completed your C out of CRUD.</p><h3>Reading</h3><p>Now we will make a function that will retrieve one of our Customer records from the database when you provide an ID number in URL:</p><pre><em>/**<br> * </em><strong><em>@Route</em></strong><em>(&quot;/customers/{id}&quot;, name=&quot;get_one_customer&quot;, methods={&quot;GET&quot;})<br> */<br></em>public function get($id): JsonResponse<br>{<br>    $customer = $this-&gt;customerRepository-&gt;findOneBy([&#39;id&#39; =&gt; $id]);<br><br>    $data = [<br>        &#39;id&#39; =&gt; $customer-&gt;getId(),<br>        &#39;firstName&#39; =&gt; $customer-&gt;getFirstName(),<br>        &#39;lastName&#39; =&gt; $customer-&gt;getLastName(),<br>        &#39;email&#39; =&gt; $customer-&gt;getEmail(),<br>        &#39;phoneNumber&#39; =&gt; $customer-&gt;getPhoneNumber(),<br>    ];<br><br>    return new JsonResponse($data, Response::<em>HTTP_OK</em>);<br>}</pre><p>Very simple function and again we use a function that’s in <em>CustomerRepository</em> by default, called <em>findOneBy</em>. Since we are getting an object as a response, we need to separate it into variables. Your postman GET request should look like this (if your link is <strong><em>{host}/customers/2)</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*DrPE3e0z8uRpT7YyqedNIg.png" /></figure><p>If you want to make another route that will fetch all the Customer records, add this function:</p><pre><em>/**<br> * </em><strong><em>@Route</em></strong><em>(&quot;/customers&quot;, name=&quot;get_all_customers&quot;, methods={&quot;GET&quot;})<br> */<br></em>public function getAll(): JsonResponse<br>{<br>    $customers = $this-&gt;customerRepository-&gt;findAll();<br>    $data = [];<br><br>    foreach ($customers as $customer) {<br>        $data[] = [<br>            &#39;id&#39; =&gt; $customer-&gt;getId(),<br>            &#39;firstName&#39; =&gt; $customer-&gt;getFirstName(),<br>            &#39;lastName&#39; =&gt; $customer-&gt;getLastName(),<br>            &#39;email&#39; =&gt; $customer-&gt;getEmail(),<br>            &#39;phoneNumber&#39; =&gt; $customer-&gt;getPhoneNumber(),<br>        ];<br>    }<br><br>    return new JsonResponse($data, Response::<em>HTTP_OK</em>);<br>}</pre><h3>UPDATING</h3><p>In the beginning of the tutorial I mentioned that I will be explaining the difference between PUT and PATCH. When you want to update the whole object you should use PUT method, but when you want to partially update an existing object you will use the PATCH method. In this example I will be using only PUT method, but will use some other schemes to see if our object is going to be fully updated. I will make <em>updateCustomer</em> function that receives the ID of customer we want to update and a request with the data we want to modify. Before we pass the variables to our <em>updateCustomer</em> function we have to check if they are empty. The function looks like this:</p><pre><em>/**<br> * </em><strong><em>@Route</em></strong><em>(&quot;/customers/{id}&quot;, name=&quot;update_customer&quot;, methods={&quot;PUT&quot;})<br> */<br></em>public function update($id, Request $request): JsonResponse<br>{<br>    $customer = $this-&gt;customerRepository-&gt;findOneBy([&#39;id&#39; =&gt; $id]);<br>    $data = json_decode($request-&gt;getContent(), true);<br><br>    empty($data[&#39;firstName&#39;]) ? true : $customer-&gt;setFirstName($data[&#39;firstName&#39;]);<br>    empty($data[&#39;lastName&#39;]) ? true : $customer-&gt;setLastName($data[&#39;lastName&#39;]);<br>    empty($data[&#39;email&#39;]) ? true : $customer-&gt;setEmail($data[&#39;email&#39;]);<br>    empty($data[&#39;phoneNumber&#39;]) ? true : $customer-&gt;setPhoneNumber($data[&#39;phoneNumber&#39;]);<br><br>    $updatedCostumer = $this-&gt;customerRepository-&gt;updateCustomer($customer);<br><br>    return new JsonResponse($updatedCostumer-&gt;toArray(), Response::<em>HTTP_OK</em>);<br>}</pre><p><em>CustomerRepository</em> also needs a new update, the <em>updateCustomer</em> function:</p><pre>public function updateCustomer(Customer $customer): Customer<br>{<br>    $this-&gt;manager-&gt;persist($customer);<br>    $this-&gt;manager-&gt;flush();<br><br>    return $customer;<br>}</pre><p>Now our Postman is looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xesMSoDhNHtJ5E1lQPpOA.png" /></figure><p>This has modified our Customer with ID number one. We changed everything, except his last name. So if you want to check out if your user truly changed in the database, you can use your own function that we wrote earlier <em>getOneCustomer</em>.</p><h3><strong>DELETING</strong></h3><p>The last letter of our CRUD tutorial is ready to be written in a form of function. We want to delete a record from our database. No problem, we will provide our function an ID and it will delete the record for us:</p><pre><em>/**<br> * </em><strong><em>@Route</em></strong><em>(&quot;/customers/{id}&quot;, name=&quot;delete_customer&quot;, methods={&quot;DELETE&quot;})<br> */<br></em>public function delete($id): JsonResponse<br>{<br>    $customer = $this-&gt;customerRepository-&gt;findOneBy([&#39;id&#39; =&gt; $id]);<br><br>    $this-&gt;customerRepository-&gt;removeCustomer($customer);<br><br>    return new JsonResponse([&#39;status&#39; =&gt; &#39;Customer deleted&#39;], Response::<em>HTTP_NO_CONTENT</em>);<br>}</pre><p>Almost there - <em>CustomerRepository</em> is missing our <em>removeCustomer</em> function. It’s very simple and probably the smallest function we will write today:</p><pre>public function removeCustomer(Customer $customer)<br>{<br>    $this-&gt;manager-&gt;remove($customer);<br>    $this-&gt;manager-&gt;flush();<br>}</pre><p>Try it out with your Postman request! Delete any number you like between 1 and 50. Or delete them all, I leave it up to you.</p><h3><strong>Swagging</strong></h3><p>Swagger is an Open Source API documentation tool that can, in an easy way help you test and document your APIs. If you document your controllers and functions the way Swagger understands it, he will automatically generate a testable list of your endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R36nHDnQ9i7vizbSJqTb1g.png" /></figure><p>Unfortunately, Swagger is not yet compatible in Symfony 5.0 version due to requirements of other components that are provided automatically with framework (framework-extra-bundle). But I will make sure to keep this up to date when new version of <em>NelmioAPI</em> comes out.</p><p>In the meantime, you can find the whole project here:</p><p><a href="https://github.com/LukaGado/Symfony5---The-REST-the-CRUD-and-the-Swag">LukaGado/Symfony5---The-REST-the-CRUD-and-the-Swag</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7430cb84cd5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/q-software/symfony-5-the-rest-the-crud-and-the-swag-7430cb84cd5">Symfony 5 — The REST, the CRUD and the Swag</a> was originally published in <a href="https://medium.com/q-software">Q agency</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Symfony and RabbitMQ]]></title>
            <link>https://medium.com/q-software/symfony-and-rabbitmq-86b14dd604b1?source=rss-98e8c33750dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/86b14dd604b1</guid>
            <category><![CDATA[q-engineering]]></category>
            <category><![CDATA[q-software]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[symfony4]]></category>
            <category><![CDATA[example]]></category>
            <dc:creator><![CDATA[Luka Gado]]></dc:creator>
            <pubDate>Wed, 20 Nov 2019 08:03:53 GMT</pubDate>
            <atom:updated>2019-11-20T09:41:37.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*hQACHyjnvK4NNthHNeGavA.png" /></figure><p>For boosting up the performances of your web applications to the maximum we often need to use some sort of queues to perform time consuming tasks. One of the best examples for doing that is <strong>RabbitMQ.</strong></p><p>RabbitMQ is lightweight and easy to deploy on premises and in the cloud. It supports multiple messaging protocols.</p><p>In this short tutorial we will be setting up fresh Symfony 4.3 project with RabbitMQ and show few examples of using them in distributing payloads to different users — messaging application.</p><h3><strong>Why RabbitMQ?</strong></h3><ul><li><strong>Reliability</strong> — Offering a variety of features including performance with minimum loss and persistence.</li><li><strong>Flexible</strong> Routing — Before messages come to the queue they are routed through exchanges. Exchanges are used for typical routing logic.</li><li><strong>Clustering </strong>— Several RabbitMQ servers on a local network can be clustered together, forming a single logical broker.</li><li><strong>Federation </strong>— For servers that need to be more loosely and unreliably connected than clustering allows, RabbitMQ offers a federation model.</li><li><strong>Multi-protocol </strong>— Variety of messaging protocols — AMQP 0–9–1, STOMP, MQTT, AMQP 1.0, HTTP and WebSockets.</li></ul><h3><strong>Requirements</strong></h3><ul><li>Symfony 4.3</li><li>RabbitMQ Bundle</li><li>Symfony Annotations</li><li>Faker</li><li>Rabbit Server</li></ul><h3><strong>Getting Started</strong></h3><p>To get you started create a new Symfony 4.3 project using Symfony command in the terminal:</p><pre><em>symfony new project-name</em></pre><p>or with the PHP dependency manager Composer:</p><pre><em>composer create-project symfony/website-skeleton project-name</em></pre><p>Inside your newly created Symfony project open up the terminal and install the RabbitMQ bundle using this command:</p><pre><em>composer require php-amqplib/rabbitmq-bundle</em></pre><p>This will also create a folder called “Consumer” which we can delete since we will be organizing our folders differently.</p><p>For easier route defining Symfony allows you to use annotation routes instead of defining them in YAML file:</p><pre><em>composer require annotations</em></pre><p>And Faker for easy creation of mocked data for our messages:</p><pre><em>composer require fzaninotto/faker</em></pre><p>We need a RabbitMQ server now. We will set it up locally (don’t worry its easy). For MacOS we will use <strong>homebrew</strong>.</p><pre><em>brew update</em><br><em>brew install rabbitmq</em><br><em>export PATH=$PATH:/usr/local/opt/rabbitmq/sbin</em><br><em>rabbitmq-server (to start the server)</em></pre><p>Your RabbitMQ dashboard is available at:</p><pre><em>http:// </em><a href="http://localhost:15672/"><em>http://localhost:15672/</em></a></pre><p>You can access your dashboard with username and password “guest”.</p><p>In the folder you will find an environment file .env with already automatically added variable for connecting to the localhost RabbitMQ server.</p><pre>###&gt; php-amqplib/rabbitmq-bundle ###<br>RABBITMQ_URL=amqp://guest:guest@localhost:5672<br>###&lt; php-amqplib/rabbitmq-bundle ###</pre><p>Automatically when RabbitMQ bundle was installed you will also get a configuration file stored in <strong>/config/packages/ </strong>called <em>old_sound_rabbit_mq.yaml</em></p><pre><strong>old_sound_rabbit_mq</strong>:<br>    <strong>connections</strong>:<br>        <strong>default</strong>:<br>            <strong>url</strong>: &#39;%env(RABBITMQ_URL)%&#39;<br>            <strong>read_write_timeout</strong>: 4<br>            <strong>heartbeat</strong>: 2<br>    <strong>producers</strong>:<br>        <strong>messaging</strong>:<br>            <strong>connection</strong>:       default<br>            <strong>exchange_options</strong>: { <strong>name</strong>: &#39;qMessages&#39;, <strong>type</strong>: direct }<br>    <strong>consumers</strong>:<br>        <strong>messaging</strong>:<br>            <strong>connection</strong>:       default<br>            <strong>exchange_options</strong>: { <strong>name</strong>: &#39;qMessages&#39;, <strong>type</strong>: direct }<br>            <strong>queue_options</strong>:    { <strong>name</strong>: &#39;qMessages&#39;}<br>            <strong>callback</strong>:         message_service<br>            <strong>enable_logger</strong>:    true</pre><ul><li><strong>producer </strong>— Sending the message to the broker.</li><li><strong>consumer</strong> — Receiving the messages.</li><li><strong>heartbeat</strong> — AMQP 0–9–1 offers a heartbeat feature to ensure that the application layer promptly finds out about disrupted connections (and also completely unresponsive peers). Heartbeats also defend against certain network equipment which may terminate “idle” TCP connections.</li></ul><p>There are also four types of exchange options we can give to our configuration file:</p><ul><li><strong>direct </strong>— sent directly to the written queue</li><li><strong>fanout </strong>— to all the queues</li><li><strong>headers </strong>— sent to queue based on the headers property</li><li><strong>topic </strong>— sent to one or more queues based on a correspondence between the routing key and the routing pattern</li></ul><p>Now we need to setup the “qMessages” exchange on our Rabbit server. We can do that with the following command</p><pre><em>php bin/console rabbitmq:setup-fabric</em></pre><p>Your RabbitMQ Management Dashboard should look like this now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pVCKN2dNOY7PLIRkdwkKQ.png" /></figure><p>The only thing left to do before we can send our message is binding our producer service to a class.</p><p>In <em>old_sound_rabbit_mq.yml</em> file add “class” to the producer like this:</p><pre><strong>producers</strong>:<br>    <strong>messaging</strong>:<br>        <strong>class</strong>: App\Rabbit\MessagingProducer<br>        <strong>connection</strong>:       default<br>        <strong>exchange_options</strong>: { <strong>name</strong>: &#39;qMessages&#39;, <strong>type</strong>: direct }</pre><p>In your <em>services.yaml </em>we need to register both Consumer and Producer:</p><pre><strong>message_service</strong>:<br>    <strong>class</strong>: App\Rabbit\MessageConsumer<br><br><strong>App\Rabbit\MessagingProducer</strong>: &#39;@old_sound_rabbit_mq.messaging_producer&#39;</pre><p>Now create a new folder called Rabbit and inside create a new class called MessagingProducer with an empty body. We will keep this very simple, so our class looks like this:</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Rabbit;<br><br><strong>use </strong>Symfony\Component\HttpFoundation\JsonResponse;<br><br><strong>class </strong>MessagingProducer <strong>extends </strong>\OldSound\RabbitMqBundle\RabbitMq\Producer<br>{<br>}</pre><h3><strong>Sending your first message!</strong></h3><p>Lets start by making a MessageService class in our service folder.</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Service;<br><br><strong>use </strong>App\Rabbit\MessagingProducer;<br><strong>use </strong>Faker\Factory;<br><strong>use </strong>Symfony\Component\HttpFoundation\JsonResponse;<br><br><strong>class </strong>MessageService<br>{<br>    <strong>private </strong>$messagingProducer;<br><br>    <strong>public function </strong>__construct(MessagingProducer $messagingProducer)<br>    {<br>        $this-&gt;messagingProducer = $messagingProducer;<br>    }<br><br>    <strong>public function </strong>createMessage(int $numberOfUsers): JsonResponse<br>    {<br>        $faker = Factory::<em>create</em>();<br><br>        <strong>for </strong>($i=0; $i&lt;$numberOfUsers; $i++) {<br>            $message = json_encode([<br>                &#39;sender&#39; =&gt; $faker-&gt;companyEmail,<br>                &#39;receiver&#39; =&gt; $faker-&gt;email,<br>                &#39;message&#39; =&gt; $faker-&gt;text,<br>            ]);<br><br>            $this-&gt;messagingProducer-&gt;publish($message);<br>        }<br><br>        <strong>return new </strong>JsonResponse([&#39;status&#39; =&gt; &#39;Sent!&#39;]);<br>    }<br>}</pre><p>We have injected our MessagingProducer class with empty body mentioned above. Also we created the createMessage with Faker Factory used for mocking up our data depending on our . Simple function for creating our messages that will be sent to the queue.</p><p>Now we can make our MessageController in the Controller folder and add a function called sendMessage. With the annotation add the route with the slug “numberOfMessages” in the URL.</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Controller;<br><br><strong>use </strong>App\Service\MessageService;<br><strong>use </strong>Symfony\Component\HttpFoundation\JsonResponse;<br><strong>use </strong>Symfony\Component\Routing\Annotation\Route;<br><br><strong>class </strong>MessageController<br>{<br>    <strong>private </strong>$messageService;<br><br>    <strong>public function </strong>__construct(MessageService $messageService)<br>    {<br>        $this-&gt;messageService = $messageService;<br>    }<br><br>    <em>/**<br>     * </em><strong><em>@Route</em></strong><em>(&quot;/send-message/{numberOfMessages}&quot;, name=&quot;send_message&quot;, methods={&quot;GET&quot;})<br>     */<br>    </em><strong>public function </strong>createMessages($numberOfMessages): JsonResponse<br>    {<br>        $this-&gt;messageService-&gt;createMessage($numberOfMessages);<br><br>        <strong>return new </strong>JsonResponse([&#39;status&#39; =&gt; &#39;Sent!&#39;]);<br>    }<br>}</pre><p>In terminal write the command:</p><pre><em>symfony server:start</em></pre><p>and now just go to the link the server provided you:</p><pre><a href="http://127.0.0.1:8000/send-message/2"><em>http://127.0.0.1:8000/send-message/2</em></a></pre><p>And voila! You have successfully sent two random generated messages to your queue!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5cx0uJzutKh20iwutva3w.png" /></figure><h3><strong>Let’s Consume our messages!</strong></h3><p>When I say Consume, I mean we actually want to collect them from our Rabbit queue and process them the way we want. Here we will define a simple class for collecting and showing our messages from the queue.</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Rabbit;<br><br><strong>use </strong>OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;<br><strong>use </strong>PhpAmqpLib\Message\AMQPMessage;<br><br><strong>class </strong>MessageConsumer <strong>implements </strong>ConsumerInterface<br>{<br><br>    <strong>public function </strong>execute(AMQPMessage $msg)<br>    {<br>        $message = json_decode($msg-&gt;body, <strong>true</strong>);<br><br>        <strong>echo </strong>&#39;Received a message from &#39;.$message[&#39;sender&#39;];<br>    }<br>}</pre><p>Now we need to run the command for initiating our function for collecting and displaying messages in our terminal:</p><pre><em>php bin/console rabbitmq:consumer messaging</em></pre><p>In your terminal all the messages that are displayed are automatically deleted from the queue unless you define them differently with “durable” property.</p><p>Now you can start being artistic and try out something else with the consumed messages. For example saving the consumed messages to the database. Consume half a million of messages and time the execution of your script — You will be surprised, or simply just start by using RabbitMQ in your applications.</p><p>For full source code visit — <a href="https://github.com/LukaGado/rabbitmq">https://github.com/LukaGado/rabbitmq</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86b14dd604b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/q-software/symfony-and-rabbitmq-86b14dd604b1">Symfony and RabbitMQ</a> was originally published in <a href="https://medium.com/q-software">Q agency</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>