<?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 Jose Clemente García Rodríguez on Medium]]></title>
        <description><![CDATA[Stories by Jose Clemente García Rodríguez on Medium]]></description>
        <link>https://medium.com/@joseclementegarciarodriguez?source=rss-eca6a7f28806------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9RBRWHfwiVu-6xIK</url>
            <title>Stories by Jose Clemente García Rodríguez on Medium</title>
            <link>https://medium.com/@joseclementegarciarodriguez?source=rss-eca6a7f28806------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 08:46:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joseclementegarciarodriguez/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 — Azure Provider for OAuth 2.0 Client bundle]]></title>
            <link>https://medium.com/@joseclementegarciarodriguez/symfony-azure-provider-for-oauth-2-0-client-bundle-bd9959d43ec7?source=rss-eca6a7f28806------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd9959d43ec7</guid>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[bundle]]></category>
            <dc:creator><![CDATA[Jose Clemente García Rodríguez]]></dc:creator>
            <pubDate>Sat, 17 Feb 2024 14:45:27 GMT</pubDate>
            <atom:updated>2024-02-28T15:11:07.253Z</atom:updated>
            <content:encoded><![CDATA[<h3>Symfony — Azure Provider for OAuth 2.0 Client bundle</h3><h4><em>Provides a tiny wrapper for using thenetworg/oauth2-azure inside Symfony.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRMTlp2fzRr2HJUxm5qySQ.png" /></figure><p>The <a href="https://github.com/TheNetworg/oauth2-azure">Azure Active Directory Provider for OAuth 2.0 Client package</a> serves as a great tool to streamline OAuth 2.0 integration in PHP applications.</p><p>Leveraging the capabilities of <em>TheNetworg/oauth2-azure</em> library, I have implemented a <a href="https://packagist.org/packages/m4n50n/oauth2-azure-bundle">Symfony wrapper</a> that offers a swift and straightforward solution for handling Azure logins. This wrapper provides a clear abstraction layer, simplifying the configuration and utilization of Azure authentication in Symfony applications.</p><h4>IInstallation 💻</h4><p>Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle:</p><pre>symfony composer require m4n50n/oauth2-azure-bundle</pre><h4>Configuration 📄</h4><p>Configuration of the bundle is simplified using a dedicated YAML file. Here, you can specify the necessary authentication parameters:</p><pre># config/packages/oauth2_azure.yaml<br><br>o_auth2_azure:<br>  # Required<br>  clientId: &quot;%env(AUTH_CLIEN_ID)%&quot;<br>  clientSecret: &quot;%env(AUTH_CLIENT_PASS)%&quot;<br>  tenant: &quot;%env(AUTH_TENANT)%&quot;<br>  redirectUri: &quot;%env(AUTH_REDIRECT_URI)%&quot;<br><br>  # Optional<br>  redirectToUrl: &quot;%env(bool:AUTH_REDIRECT_TO_URL)%&quot; # Activate redirect after authentication<br>  redirectUrl: &quot;%env(AUTH_REDIRECT_URL)%&quot;</pre><h4>Symfony Integration ⚙</h4><p>This bundle provides an intuitive and clean interface for OAuth 2.0 authentication in Symfony. You can integrate authentication into your controllers or services by injecting the OAuth2AzureFactory.</p><pre>use M4n50n\OAuth2AzureBundle\Factory\OAuth2AzureFactory;<br><br>final class LoginController extends AbstractController<br>{<br>    public function __construct(private OAuth2AzureFactory $OAuth2AzureFactory)<br>    {<br>    }<br><br>    #[Route(path: &#39;/login/azure&#39;, name: &#39;login_azure&#39;, methods: [&#39;GET&#39;])]<br>    public function user_azureLoginRequest(JWTTokenManagerInterface $JWTManager, UserPasswordHasherInterface $userPasswordHasher)<br>    {<br>        try {<br>            // ...<br><br>            $auth = $this-&gt;OAuth2AzureFactory-&gt;getAuth($this-&gt;request);<br>            $ownerData = $auth-&gt;getOwnerData();<br><br>            /* It returns an array with the following structure:<br><br>            $ownerData = [<br>                &quot;aud&quot; =&gt; &quot;c3db02f0-401c-452c......&quot;,<br>                &quot;iss&quot; =&gt; &quot;https://login.microsoftonline.com/....../v2.0&quot;,<br>                &quot;iat&quot; =&gt; 1360114,<br>                &quot;profileImage&quot; =&gt; &quot;&quot;, // base64_encode of the image binary<br>                &quot;email&quot;:&quot;josegarciarodriguez89@hotmail.com&quot;,<br>                &quot;name&quot;:&quot;Jose Garcia&quot;,<br>                <br>                // ... (other fields)<br>            ];              <br>            */<br><br>            // ...<br>        } catch (\Exception $exception) {<br>            // ...<br>        }<br><br>        // ...<br>    }<br>}</pre><h4>Wrapper’s Utility ❗</h4><p><strong>Integration</strong>: This bundle encapsulates the intricacies of Azure OAuth 2.0, allowing you to seamlessly integrate authentication into Symfony applications without getting bogged down by the underlying complexities.</p><ol><li><strong>Simplicity</strong>: The YAML configuration file simplifies the setup process, allowing developers to focus on the essential authentication details without navigating through extensive documentation.</li><li><strong>Security</strong>: Leveraging the proven TheNetworg/oauth2-azure library, this bundle ensures a secure authentication process, mitigating potential vulnerabilities and enhancing the overall security posture of Symfony applications.</li><li><strong>Best Practices</strong>: Built with Symfony best practices in mind, the bundle aligns with Symfony’s architecture, ensuring compatibility and adherence to established development standards.</li></ol><h4>Conclusion ✅</h4><p>In conclusion, <a href="https://packagist.org/packages/m4n50n/oauth2-azure-bundle">this bundle</a> offers robust and user-friendly solution for integrating OAuth 2.0 authentication into Symfony projects.</p><p>For a more in-depth understanding and comprehensive documentation, feel free to explore the detailed information provided in the README documentation on <a href="https://github.com/m4n50n/oauth2_azure_bundle">GitHub</a>.</p><p>▶ <a href="https://github.com/m4n50n/oauth2_azure_bundle">https://github.com/m4n50n/oauth2_azure_bundle</a></p><p>▶ <a href="https://packagist.org/packages/m4n50n/oauth2-azure-bundle">https://packagist.org/packages/m4n50n/oauth2-azure-bundle</a></p><p>Feel free to contact me if you have any questions or proposals😄.</p><p>You can follow me on <a href="https://www.linkedin.com/in/josegarciarodriguez/">LinkedIn</a> and <a href="https://github.com/m4n50n">GitHub</a>.</p><p>Thank you very much for coming here.</p><h3>Love My Work? Here is How to Support Me!</h3><p><a href="https://www.buymeacoffee.com/m4n50n">Jose Clemente García Rodríguez</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd9959d43ec7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker — Building an environment with multiple PHP versions on a single Nginx server]]></title>
            <link>https://medium.com/@joseclementegarciarodriguez/docker-building-an-environment-with-multiple-php-versions-on-a-single-nginx-server-438108addd28?source=rss-eca6a7f28806------2</link>
            <guid isPermaLink="false">https://medium.com/p/438108addd28</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Jose Clemente García Rodríguez]]></dc:creator>
            <pubDate>Sat, 21 Oct 2023 16:11:52 GMT</pubDate>
            <atom:updated>2024-02-28T15:16:03.208Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker — Building an environment with multiple PHP versions on a single Nginx server</h3><h4>A practical use case based in Nginx ports</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGnB8GwfjYSvHqQCx6_OXQ.png" /><figcaption>Docker | Nginx | PHP — Photo by <a href="https://unsplash.com/es/@scottrodgerson?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Scott Rodgerson</a> on <a href="https://unsplash.com/es/fotos/un-monton-de-cables-azules-conectados-entre-si-PSpf_XgOM5w?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>We often work with systems that run on different software versions. Therefore, we need tools that allow us to compile / interpret / execute our code according to the context where we are.</p><p>In this article we will see how to create a development environment with Docker that will allow:</p><ul><li>Use multiple PHP containers with different versions (in this guide we will install FPM 7.4 and 8.2).</li><li>Configure an Nginx container as a web server to redirect requests to the PHP container that should act as interpreter based on the URL and port.</li></ul><p>👉<em> I will explain everything in detail, but I understand that you know Docker and how it works.</em></p><h4>Getting started with Docker 🐳</h4><p>You need to have Docker installed on your machine. After that, if you don’t have a Docker Desktop environment, you can use <a href="https://www.portainer.io/">Portainer</a> for quick management of all your containers.</p><h4>Docker Compose 📑</h4><p>Docker Compose allows you to manage and define multi-container stacks using a YAML file called <em>docker-compose.yml</em>. In this file we will specify the images, ports, volumes and other instructions for each container.</p><pre>version: &quot;3.9&quot;<br>services:<br>  nginx:<br>    image: nginx:alpine    <br>    ports:<br>      - &quot;8001:80&quot;<br>      - &quot;8002:82&quot;<br>    volumes:<br>      - ./sites/:/var/www/html/<br><br>  php74:<br>    image: php:7.4-fpm<br>    volumes:<br>      - ./sites/:/var/www/html/<br><br>  php82:<br>    image: php:8.2-fpm<br>    volumes:<br>      - ./sites/:/var/www/html/<br><br>networks:<br>  multi_php_nginx:<br><br>name: multi_php_nginx</pre><ul><li>Nginx will be configured to listen on ports 80 and 82, and based on them it will redirect the requests to the corresponding PHP container.</li><li>Each container will be mapped to the <em>/sites/</em> folder, which will contain the directories corresponding to each website:</li></ul><blockquote><em>./sites/<br>— site_74/index.php</em></blockquote><blockquote><em>— site_82/index.php</em></blockquote><h4>Running containers ➡️</h4><p>To create and start the containers, open a terminal inside the folder containing the <em>docker-compose.yml</em> file and run the following command:</p><pre>$ docker compose up -d</pre><p>Finally, we have our stack of containers ready:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oBG_r3ilNL2ZeY8hw_QiTw.png" /><figcaption>Containers view on Portainer</figcaption></figure><h4>Nginx configuration ⚡</h4><p>We already have active in our <em>localhost</em> the Nginx service listening on the defined ports. We only need to modify the server configuration to redirect to the correct folder and PHP container.</p><p>You can run commands in a running container by executing the following command in your local terminal:</p><pre>$ docker exec -it -u root multi_php_nginx-nginx-1 sh</pre><p>Let’s edit the Nginx default configuration file:</p><pre>$ nano /etc/nginx/nginx.conf</pre><pre>user  nginx;<br>worker_processes  auto;<br><br>error_log  /var/log/nginx/error.log notice;<br>pid        /var/run/nginx.pid;<br><br>events {<br>    worker_connections  1024;<br>}<br><br>http {<br>    include       /etc/nginx/mime.types;<br>    default_type  application/octet-stream;<br><br>    log_format  main  &#39;$remote_addr - $remote_user [$time_local] &quot;$request&quot; &#39;<br>                      &#39;$status $body_bytes_sent &quot;$http_referer&quot; &#39;<br>                      &#39;&quot;$http_user_agent&quot; &quot;$http_x_forwarded_for&quot;&#39;;<br><br>    access_log  /var/log/nginx/access.log  main;<br><br>    sendfile        on;<br>    keepalive_timeout  65;<br><br>    include /etc/nginx/conf.d/*.conf;<br>}</pre><p>We need to add the following code inside <em>http </em>block:</p><pre># PHP 7.4 service<br>server {<br>    listen 80;<br>    server_name localhost;<br>    root /var/www/html/site_74/;<br>    index index.php index.html index.htm;<br><br>    location ~ \.php$ {<br>        fastcgi_pass php74:9000;<br>        include fastcgi_params;<br>        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;<br>    }<br>}<br><br># PHP 8.2 service<br>server {<br>    listen 82;<br>    server_name localhost;<br>    root /var/www/html/site_82/;<br>    index index.php index.html index.htm;<br><br>    location ~ \.php$ {<br>        fastcgi_pass php82:9000;<br>        include fastcgi_params;<br>        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;<br>    }<br>}</pre><p>Now save the changes and restart the Nginx service.</p><blockquote>Remember that you can also map the configuration file within Docker Compose.</blockquote><h4>How it works ❓</h4><p>When you make a request to <em>localhost:8001</em>, Nginx will listen on port 80 and define the<em> /site_74/</em> folder as the root web directory.</p><p>Also, the <em>fastcgi_pass php74:9000</em> line will specify the location of the PHP service to which Nginx will send requests for processing.</p><p>The same thing will happen when calling to <em>localhost:8002</em> and the PHP 8.2 service.</p><h4>Conclusión ✅</h4><p>Obviously, there are many ways to do this. Probably better (and also worse), but it’s a way to see how we can develop under different versions of PHP.</p><p>I hope I have explained myself well and that it has been useful to you.</p><p>Feel free to contact me if you have any questions or another solution😄.</p><p>You can follow me on <a href="https://www.linkedin.com/in/josegarciarodriguez/">LinkedIn</a> and <a href="https://github.com/m4n50n">GitHub</a>.</p><p>Thank you very much for coming here.</p><h3>Love My Work? Here is How to Support Me!</h3><p><a href="https://www.buymeacoffee.com/m4n50n">Jose Clemente García Rodríguez</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=438108addd28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interoperability between Angular models and Symfony entities for data management]]></title>
            <link>https://medium.com/@joseclementegarciarodriguez/interoperability-between-angular-models-and-symfony-entities-for-data-management-83441851c9e0?source=rss-eca6a7f28806------2</link>
            <guid isPermaLink="false">https://medium.com/p/83441851c9e0</guid>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Jose Clemente García Rodríguez]]></dc:creator>
            <pubDate>Mon, 17 Jul 2023 06:24:13 GMT</pubDate>
            <atom:updated>2024-02-28T15:16:16.696Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GlNwxGVplTfth6EpWpRKw.png" /><figcaption>Angular / TypeScript — Symfony / Doctrine ORM</figcaption></figure><p>When we develop applications that implement CRUD (Create, Read, Update, and Delete) operations, one of the most important questions we must ask ourselves is how to manage and structure information effectively.</p><p>This will help us maintain the integrity of the data in our database and it will be crucial in ensuring that any CRUD operation runs safely and efficiently.</p><p>In this article we will see how to optimize the data flow between the backend and the frontend using Symfony entities with Doctrine ORM and Angular models and services.</p><h3>What is an ORM (Object Relational Mapping)❓</h3><p>An ORM ( <em>Object Relational Mapping</em> ) is a programming model that links the tables of a database with the entities of an application.</p><p>These entities are classes whose properties represent the columns of a table, and each instance of this class represents a record of that table in the database.</p><p>In this way, an ORM allows us to interact with the database using objects instead of SQL using any object-oriented programming language that has an ORM as such.</p><p>In short, an ORM provides an abstraction layer that makes an application more flexible. One of the best features they offer is the fact of being able to interact with the database regardless of the engine being used.</p><p>This means that, in general terms, the type of database behind it becomes transparent to the ORM. In case we need to go from MySQL to PostgreSQL, for example, we would only have to change the connection strings to the database and that’s it.</p><h3>Data modeling with Symfony entities ➡️</h3><p>As we have explained in the previous section, entities in Symfony are PHP classes that represent tables and their properties represent columns.</p><blockquote>In the context of Doctrine, entities act as an interface that allows you to interact with the database through objects.</blockquote><p>For example, suppose we need to create the <em>Person</em> table.</p><p>In native SQL we would have the following code:</p><pre>CREATE  TABLE Person ( <br>  id INT  NOT  NULL  PRIMARY KEY, <br>  name VARCHAR ( 150 ) NOT  NULL , <br>  email VARCHAR ( 50 ) <br>);</pre><p>This same table would be represented in Symfony as an entity as follows:</p><pre>namespace  App \ Entity ; <br><br>use  Doctrine \ ORM \ Mapping  as  ORM ; <br><br>#[ORM\Entity(repositoryClass: PersonRepository::class)] <br>class  Person<br> { <br>  #[ORM\Id] <br>  #[ORM\GeneratedValue] <br>  #[ORM\Column] <br>  private ? int  $id = null ; <br><br>  #[ORM\Column(length: 150)] <br>  private ? string  $name = null ; <br><br>  #[ORM\Column(length: 50, nullable: true)] <br>  private ? string  $email =null ; <br><br>  public  function  getId ( ): ? int<br>   { <br>    return  $this- &gt;id; <br>  } <br><br>  public  function  getName ( ): ? string<br>   { <br>    return  $this- &gt;name; <br>  } <br><br>  public  function  setName ( string  $name ): self<br>   { <br>    $this -&gt;name = $name ; <br>    return  $this ; <br>  } <br><br>  public  function  getEmail ( ): ? string<br>   { <br>    return $this- &gt;email; <br>  } <br><br>  public  function  setEmail ( ? string  $email ): self<br>   { <br>    $this -&gt;email = $email ; <br>    return  $this ; <br>  } <br>}</pre><p>In the previous code we can see that in addition to the properties, <em>getters</em> and <em>setters</em> are defined , which are methods that allow obtaining and assigning values ​​to the columns for a specific record.</p><p>It is important to understand that when using entities we are creating representations of the data in code and we are also defining rules, constraints and mechanisms that ensure the integrity of said data and also help us prevent and control errors.</p><p>In fact, in entities we can add additional control methods or even define methods that respond to events in a similar way to database <em>triggers , for example.</em></p><h4>▪ Create records</h4><p>We can create a new record as follows:</p><pre>use  App \ Entity \ Person ; <br>use  Doctrine \ ORM \ EntityManagerInterface ; <br><br>// ... <br><br>public  function  createPerson ( EntityManagerInterface $entityManager )<br> { <br>  $newPerson = new  Person (); // Create a new instance of the Person entity <br>  $newPerson -&gt; setName ( &quot;Norman Bates&quot; ); // Assign the value of the &#39;name&#39; column <br>  $newPerson -&gt; setEmail ( &quot;norman@email.com&quot;); // Assign the value of the &#39;email&#39; column <br><br>  // At this point we would already have the object referring to the new record, so the only thing left would be to save it in the database <br>  $entityManager -&gt; persist ( $newPerson ); // Prepare the instance to be stored <br>  $entityManager -&gt; flush (); // Doctrine executes the insert in the database and ends the process<br> }</pre><h4>▪ Get records</h4><p>Doctrine has several methods through the repositories of each entity to obtain records. For example:</p><pre>/ ... <br><br>$personRepository = $this -&gt; getDoctrine ()-&gt; getRepository ( Person :: class ); <br>$persons = $personRepository -&gt; findAll ();</pre><p>In this case, <em>$persons</em> will be an array of <em>Person</em> objects , each representing a record from the <em>Person</em> table.</p><h4>▪ Modify records</h4><p>From here the mechanics will always be the same, so we could do the following:</p><pre>// ... <br><br>$firstArrayItem = $persons [ 0 ]; // Get the first result returned by the api and store it in a variable <br><br>$email = $firstArrayItem -&gt; getEmail (); // Get the email and store it in a variable <br><br>$firstArrayItem -&gt; setName ( &quot;Patrick Bateman&quot; ); // Modify the value of the &#39;name&#39; column</pre><p>👆 In order for any modification to be reflected in the database, it will be necessary to call the <em>persist()</em> and <em>flush()</em> methods again.</p><h3>Data modeling with Angular models ➡️</h3><p>In Angular, models are TypeScript classes that represent the structure of the data to be handled in the application, providing a consistent way to manage the data.</p><p>Like entities in Symfony, in Angular models each property corresponds to a column or field and an instance of a model represents a record of that model.</p><p>A simple example of a <em>Person</em> model in Angular would be the following:</p><pre>export  class  Person { <br>  id : number ; <br>  name : string ; <br>  email?: string ; <br>}</pre><p>But <strong>how do these models connect to Symfony entities?</strong></p><p>In our case, Angular models will represent <strong>the same data structures as Symfony entities</strong>.</p><p>When the frontend receives data from the backend we will use the models to “type” said data taking advantage of Typescript’s type system.</p><p>In the next point we will see how to keep the database objects that we receive and send to the api typed and intact.</p><h3>Service for CRUD operations in Angular ⚡</h3><p>Although the ideal is to have dynamic services and models that can be extended (through inheritance, for example) by the services and models of each entity avoiding code repetition (DRY — Don’t Repeat <em>Yourself</em>), we are going to create a service concrete for the <em>Person </em>entity that will only use the <em>Person </em>model for better understanding.</p><p>First, let’s modify the model we saw earlier:</p><pre>export  class  Person { <br>  public  id : string ; <br>  public  name : string ; <br>  public email?: string ; <br><br>  constructor ( person?: Partial&lt;Person&gt; ) { <br>    if (person) { Object . assign ( this , person); } <br>  } <br>}</pre><p>We define a constructor that allows the model to be instantiated from an object of the same. That is, when the backend returns a record from the <em>Person</em> table of the database, we can do the following:</p><pre>const person = new  Person ({ <br>  id : 1 <br>  name : &quot;Paul Allen&quot; <br>  email : &quot;paul@email.com&quot;<br> })</pre><p>In this way we would achieve one of the goals of this article: typing a database object just like in Symfony.</p><p>Now we are going to create the <em>PersonService </em>with the following methods:</p><h4>▶ Create a record</h4><p>The <em>create()</em> method receives an object of type <em>Person</em> and returns the object created on the server converted to an instance of the model class.</p><h4>▶ Get all records</h4><p>The <em>getAll()</em> method returns a list of all existing records in the database’s <em>Person </em>table, which is iterated over to make each record an instance of the model class.</p><h4>▶ Get a record</h4><p>The <em>getOne()</em> method receives the ID of the record we want to query in the database and returns it instantiated in the <em>Person</em> model.</p><h4>▶ Update a record</h4><p><em>The update()</em> method receives an object of type <em>Person</em> and returns an instance of the updated record on the server.</p><h4>▶ Delete a record</h4><p><em>The delete()</em> method receives the ID of the record that we want to completely delete and returns nothing.</p><p><em>1️⃣ The methods return instances of the Person</em> model class to guarantee that the data we receive conforms to the structure we expect and also to be able to use all the additional functionalities and methods that have been defined in that model.</p><p>2️⃣ All the methods return <em>Observables</em> so that the components that subscribe to them are in charge of carrying out the appropriate tasks according to the need, such as controlling errors or calling other methods.</p><p>3️⃣ The methods that receive an object of type <em>Person</em> allow you to do it partially (<em>Partial&lt;Person&gt;</em>), since it is possible that when a record is created, for example, some properties are not yet available.</p><p>The service code would be as follows:</p><pre>import { HttpClient } from  &#39;@angular/common/http&#39; ; <br><br>// RxJs <br>import { Observable } from  &#39;rxjs&#39; ; <br>import { map } from  &#39;rxjs/operators&#39; ; <br><br>import { Person } from  &#39;./person.model&#39; ; <br><br>export  class  PersonService { <br>  private  apiUrl : string = &#39;https://api-url&#39; ; <br><br>  constructor ( private httpClient: HttpClient ) {} <br><br>  toJson(): any { <br>    return  JSON . parse ( JSON .stringify ( this ) ); <br>  } <br><br>  create ( person : Partial &lt; Person &gt;): Observable &lt; Person &gt; { <br>    return  this . httpClient<br>       . post &lt; Person &gt;( this .apiUrl , person.toJson (       ) ) . pipe ( map ( ( result ) =&gt;<br> newPerson  ( result))); <br>  } <br><br>  getAll (): Observable &lt; Person []&gt; { <br>    return  this . httpClient<br>       . get &lt; Person []&gt;( this . apiUrl ) <br>      . pipe ( map ( ( result ) =&gt; result. map ( ( i ) =&gt;  new  Person (i)))); <br>  } <br><br>  getOne ( id : number ): Observable &lt; Person&gt; { <br>    return  this . httpClient<br>       . get &lt; Person &gt;( ` ${ this .apiUrl} / ${id} ` ) <br>      . pipe ( map ( ( result ) =&gt;  new  Person (result))); <br>  } <br><br>  update ( person : Partial &lt; Person &gt;): Observable &lt; Person &gt; { <br>    return  this . httpClient<br>       . put &lt; Person&gt;( ` ${ this .apiUrl } ` , person.toJson ()) <br>      . pipe ( map ( ( result ) =&gt;  new  Person (result))); <br>  } <br><br>  delete ( id : number ): Observable &lt; void &gt; { <br>    return  this . httpClient . delete &lt; void &gt;( ` ${ this .apiUrl} / ${id} ` ); <br>  } <br>}</pre><p>What is really interesting is the fact of being able to work with classes following practically the same mechanics in the frontend and in the backend, working in a more intuitive and organized way, which indirectly leads us to create cleaner <strong>and more maintainable code</strong>.</p><h3>Conclusion ✅</h3><p>Here the article! I hope I have explained myself well and that it has been useful to you.</p><p>The intention is to improve the code of your applications making it more generic and reusable 🎯.</p><p>Feel free to contact me if you have any questions.</p><p>You can follow me on <a href="https://www.linkedin.com/in/josegarciarodriguez/">LinkedIn</a> and <a href="https://github.com/m4n50n">GitHub</a>.</p><p>Thank you very much for coming here.</p><h3>Love My Work? Here is How to Support Me!</h3><p><a href="https://www.buymeacoffee.com/m4n50n">Jose Clemente García Rodríguez</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83441851c9e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interoperabilidad entre los modelos de Angular y las entidades de Symfony para la gestión de datos]]></title>
            <link>https://medium.com/@joseclementegarciarodriguez/interoperabilidad-entre-los-modelos-de-angular-y-las-entidades-de-symfony-para-la-gesti%C3%B3n-de-datos-b65aa04258ad?source=rss-eca6a7f28806------2</link>
            <guid isPermaLink="false">https://medium.com/p/b65aa04258ad</guid>
            <category><![CDATA[datos]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[full-stack]]></category>
            <dc:creator><![CDATA[Jose Clemente García Rodríguez]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 18:08:33 GMT</pubDate>
            <atom:updated>2023-08-11T19:45:03.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GlNwxGVplTfth6EpWpRKw.png" /><figcaption>Angular / TypeScript — Symfony / Doctrine ORM</figcaption></figure><p>Cuando desarrollamos aplicaciones que implementan operaciones CRUD (Crear, Leer, Actualizar y Borrar), una de las cuestiones más importantes que debemos plantearnos es cómo gestionar y estructurar la información de forma eficaz.</p><p>Esto no sólo nos ayudará a mantener la integridad de los datos de nuestra base de datos, sino que será crucial para garantizar que cualquier operación CRUD se ejecute de forma segura y eficiente.</p><p>En este artículo veremos cómo optimizar el flujo de datos entre el backend y el frontend utilizando las entidades de Symfony con su ORM Doctrine y los modelos y servicios de Angular.</p><h3>Qué es un ORM (Mapeo Relacional de Objetos)❓</h3><p>Un ORM (<em>Object Relational Mappig</em>) es un modelo de programación que vincula las tablas de una base de datos con las entidades de una aplicación.</p><p>Estas entidades no son más que clases cuyas propiedades representan las columnas de una tabla, y a su vez, cada instancia de dicha clase representa un registro de esa tabla en la base de datos.</p><p>De esta manera, un ORM nos permite interactuar con la base de datos utilizando objetos en lugar de SQL con cualquier lenguaje de programación orientado a objetos que disponga de un ORM como tal.</p><p>En definitiva, un ORM proporciona una capa de abstracción que hace que una aplicación sea más flexible, y sin duda una de las mejores características que ofrecen es el hecho de poder interactuar con la base de datos independientemente del motor que se esté usando.</p><p>Esto significa que, en términos generales, para el ORM llega a ser transparente el tipo de base de datos que hay detrás. Así, en caso de que necesitemos pasar de MySQL a PostgreSQL, por ejemplo, únicamente tendríamos que cambiar las cadenas de conexión a la base de datos y listo.</p><h3>Modelado de datos con entidades de Symfony ➡️</h3><p>Como hemos explicado en el apartado anterior, las entidades en Symfony son clases PHP que representan tablas y sus propiedades representan columnas.</p><blockquote>En el contexto de Doctrine, las entidades actúan como una interfaz que permite interactuar con la base de datos a través de objetos.</blockquote><p>Por ejemplo, supongamos que necesitamos crear la tabla <em>Person</em>.</p><p>En SQL nativo tendríamos el siguiente código:</p><pre>CREATE TABLE Person (<br>  id INT NOT NULL PRIMARY KEY,<br>  name VARCHAR(150) NOT NULL,<br>  email VARCHAR(50)<br>);</pre><p>Esta misma tabla se representaría en Symfony como una entidad de la siguiente manera:</p><pre>namespace App\Entity;<br><br>use Doctrine\ORM\Mapping as ORM;<br><br>#[ORM\Entity(repositoryClass: PersonRepository::class)]<br>class Person<br>{<br>  #[ORM\Id]<br>  #[ORM\GeneratedValue]<br>  #[ORM\Column]<br>  private ?int $id = null;<br><br>  #[ORM\Column(length: 150)]<br>  private ?string $name = null;<br><br>  #[ORM\Column(length: 50, nullable: true)]<br>  private ?string $email = null;<br><br>  public function getId(): ?int<br>  {<br>    return $this-&gt;id;<br>  }<br><br>  public function getName(): ?string<br>  {<br>    return $this-&gt;name;<br>  }<br><br>  public function setName(string $name): self<br>  {<br>    $this-&gt;name = $name;<br>    return $this;<br>  }<br><br>  public function getEmail(): ?string<br>  {<br>    return $this-&gt;email;<br>  }<br><br>  public function setEmail(?string $email): self<br>  {<br>    $this-&gt;email = $email;<br>    return $this;<br>  }<br>}</pre><p>En el código anterior podemos ver que además de las propiedades se definen los <em>getters </em>y <em>setters</em>, que son métodos que permiten obtener y asignar valores a las columnas para un registro específico.</p><p>Es importante entender que al usar entidades no sólo estamos creando representaciones de los datos en el código, sino que también estamos definiendo reglas, restricciones y mecanismos que aseguran la integridad de dichos datos y además nos ayudan a prevenir y controlar errores.</p><p>De hecho, en las entidades podemos añadir métodos de control adicionales o incluso definir métodos que respondan a eventos de forma similar a los <em>triggers </em>de base de datos, por ejemplo.</p><h4>▪ <strong>Crear registros</strong></h4><p>Podemos crear un nuevo registro de la siguiente manera:</p><pre>use App\Entity\Person;<br>use Doctrine\ORM\EntityManagerInterface;<br><br>// ...<br><br>public function createPerson(EntityManagerInterface $entityManager)<br>{<br>  $newPerson = new Person(); // Creamos una nueva instancia de la entidad Person<br>  $newPerson-&gt;setName(&quot;Norman Bates&quot;); // Asignamos el valor de la columna &#39;name&#39;<br>  $newPerson-&gt;setEmail(&quot;norman@email.com&quot;); // Asignamos el valor de la columna &#39;email&#39;<br><br>  // En este momento ya dispondríamos del objeto referente al nuevo registro, así que lo único que quedaría sería guardarlo en la base de datos<br>  $entityManager-&gt;persist($newPerson); // Se prepara la instancia para ser almacenada<br>  $entityManager-&gt;flush(); // Doctrine ejecuta el insert en la base de datos y finaliza el proceso<br>}</pre><h4>▪ <strong>Obtener registros</strong></h4><p>Doctrine dispone de varios métodos a través de los repositorios de cada entidad para obtener registros. Por ejemplo:</p><pre>// ...<br><br>$personRepository = $this-&gt;getDoctrine()-&gt;getRepository(Person::class);<br>$persons = $personRepository-&gt;findAll();</pre><p>En este caso, <em>$persons</em> será un array de objetos <em>Person</em>, y cada uno representará un registro de la tabla <em>Person</em>.</p><h4>▪ <strong>Modificar registros</strong></h4><p>A partir de aquí la mecánica siempre será la misma, así que podríamos hacer lo siguiente:</p><pre>// ...<br><br>$firstArrayItem = $persons[0]; // Obtenemos el primer resultado devuelto por la api y lo guardamos en una variable<br><br>$email = $firstArrayItem-&gt;getEmail(); // Obtenemos el email y lo guardamos en una variable<br><br>$firstArrayItem-&gt;setName(&quot;Patrick Bateman&quot;); // Modificamos el valor de la columna &#39;name&#39;</pre><p>👆 Para que cualquier modificación se refleje en la base de datos será necesario llamar de nuevo a los métodos <em>persist()</em> y <em>flush()</em>.</p><h3>Modelado de datos con modelos de Angular ➡️</h3><p>En Angular, los modelos son clases de TypeScript que representan la estructura de los datos que se van a manejar en la aplicación, proporcionando una forma consistente de gestionar los datos.</p><p>Al igual que las entidades en Symfony, en los modelos de Angular cada propiedad se corresponde con una columna o campo y una instancia de un modelo representa un registro de dicho modelo.</p><p>Un ejemplo simple de modelo <em>Person </em>en Angular sería el siguiente:</p><pre>export class Person {<br>  id: number;<br>  name: string;<br>  email?: string;<br>}</pre><p>Pero, <strong>¿cómo se conectan estos modelos con las entidades de Symfony?</strong></p><p>En nuestro caso, los modelos de Angular representarán <strong>las mismas estructuras de datos que las entidades de Symfony</strong>.</p><p>Cuando el frontend reciba datos del backend utilizaremos los modelos para “tipar” dichos datos aprovechando el sistema de tipos de Typescript.</p><p>En el siguiente punto veremos cómo mantener tipados e intactos los objetos de base de datos que recibimos y enviamos a la api.</p><h3><strong>Servicio para operaciones CRUD en Angular ⚡</strong></h3><p>Aunque lo ideal es disponer de servicios y modelos dinámicos que puedan ser extendidos (mediante herencias, por ejemplo) por los servicios y modelos propios de cada entidad evitando la repetición de código (<em>DRY — Don’t Repeat Yourself</em>), vamos a crear un servicio concreto para la entidad <em>Person </em>que usará únicamente el modelo <em>Person </em>para que se entienda mejor.</p><p>Primero, vamos a modificar el modelo que vimos anteriormente:</p><pre>export class Person {<br>  public id: string;<br>  public name: string;<br>  public email?: string;<br><br>  constructor(person?: Partial&lt;Person&gt;) {<br>    if (person) { Object.assign(this, person); }<br>  }<br>}</pre><p>Definimos un constructor que permita instanciar el modelo a partir de un objeto del mismo. Es decir, cuando el backend devuelva un registro de la tabla <em>Person </em>de la base de datos podremos hacer lo siguiente:</p><pre>const person = new Person({<br>  id: 1<br>  name: &quot;Paul Allen&quot;<br>  email: &quot;paul@email.com&quot;<br>})</pre><p>De esta forma conseguiríamos uno de los objetivos de este artículo: tipar un objeto de la base de datos al igual que en Symfony.</p><p>Ahora vamos a crear el servicio <em>PersonService </em>con los siguientes métodos:</p><h4>▶ <strong>Crear un registro</strong></h4><p>El método <em>create()</em> recibe un objeto de tipo <em>Person </em>y devuelve el objeto creado en el servidor convertido en una instancia de la clase del modelo.</p><h4>▶ <strong>Obtener todos los registros</strong></h4><p>El método <em>getAll()</em> método devuelve una lista de todos los registros existentes en la tabla <em>Person </em>de la base de datos, la cual es iterada para convertir cada registro en una instancia de la clase del modelo.</p><h4>▶ <strong>Obtener un registro</strong></h4><p>El método <em>getOne()</em> recibe el ID del registro que queremos consultar en la base de datos y lo devuelve instanciado en el modelo <em>Person</em>.</p><h4>▶ <strong>Actualizar un registro</strong></h4><p>El método <em>update()</em> recibe un objeto de tipo <em>Person</em> y devuelve una instancia del registro actualizado en el servidor.</p><h4>▶ <strong>Eliminar un registro</strong></h4><p>El método <em>delete()</em> recibe el ID del registro que queremos eliminar por completo y no devuelve nada.</p><p>1️⃣ Los métodos devuelven instancias de la clase del modelo <em>Person </em>para garantizar que los datos que recibimos se ajusten a la estructura que esperamos y además poder utilizar todos las funcionalidades y métodos adicionales que haya definidos en ese modelo.</p><p>2️⃣ Todos los métodos devuelven <em>Observables </em>para que los componentes que se suscriban a ellos sean los encargados de realizar las tareas oportunas según la necesidad, como controlar errores o llamar a otros métodos.</p><p>3️⃣ Los métodos que reciben un objeto de tipo <em>Person </em>permiten hacerlo parcialmente (<em>Partial&lt;Person&gt;</em>), ya que es posible que cuando se crea un registro, por ejemplo, algunas propiedades aún no estén disponibles.</p><p>El código del servicio quedaría de la siguiente manera:</p><pre>import { HttpClient } from &#39;@angular/common/http&#39;;<br><br>// RxJs<br>import { Observable } from &#39;rxjs&#39;;<br>import { map } from &#39;rxjs/operators&#39;;<br><br>import { Person } from &#39;./person.model&#39;;<br><br>export class PersonService {<br>  private apiUrl: string = &#39;https://api-url&#39;;<br><br>  constructor(private httpClient: HttpClient) {}<br><br>  toJson(): any {<br>    return JSON.parse(JSON.stringify(this));<br>  }<br><br>  create(person: Partial&lt;Person&gt;): Observable&lt;Person&gt; {<br>    return this.httpClient<br>      .post&lt;Person&gt;(this.apiUrl, person.toJson())<br>      .pipe(map((result) =&gt; new Person(result)));<br>  }<br><br>  getAll(): Observable&lt;Person[]&gt; {<br>    return this.httpClient<br>      .get&lt;Person[]&gt;(this.apiUrl)<br>      .pipe(map((result) =&gt; result.map((i) =&gt; new Person(i))));<br>  }<br><br>  getOne(id: number): Observable&lt;Person&gt; {<br>    return this.httpClient<br>      .get&lt;Person&gt;(`${this.apiUrl}/${id}`)<br>      .pipe(map((result) =&gt; new Person(result)));<br>  }<br><br>  update(person: Partial&lt;Person&gt;): Observable&lt;Person&gt; {<br>    return this.httpClient<br>      .put&lt;Person&gt;(`${this.apiUrl}`, person.toJson())<br>      .pipe(map((result) =&gt; new Person(result)));<br>  }<br><br>  delete(id: number): Observable&lt;void&gt; {<br>    return this.httpClient.delete&lt;void&gt;(`${this.apiUrl}/${id}`);<br>  }<br>}</pre><p>Lo verdaderamente interesante es el hecho de poder trabajar con clases siguiendo prácticamente la misma mecánica en el frontend y en el backend trabajando de una forma más intuitiva y organizada, lo que indirectamente nos lleva a crear <strong>código más limpio y mantenible</strong>.</p><h3><strong>Conclusión ✅</strong></h3><p>Hasta aquí el artículo! Espero haberme explicado bien y que te haya sido de utilidad.</p><p>La intención es mejorar el código de tus aplicaciones haciéndolo más genérico y reutilizable 🎯.</p><p>No dudes en ponerte en contacto conmigo si tienes alguna pregunta.</p><p>Puedes seguirme en <a href="https://www.linkedin.com/in/josegarciarodriguez/">LinkedIn</a> y <a href="https://github.com/m4n50n">GitHub</a>.</p><p>Muchas gracias por llegar hasta aquí.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b65aa04258ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Data Binding — What is it?]]></title>
            <link>https://medium.com/@joseclementegarciarodriguez/angular-data-binding-what-is-it-7d7c8a93a1c4?source=rss-eca6a7f28806------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d7c8a93a1c4</guid>
            <category><![CDATA[data-binding]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[event-binding]]></category>
            <dc:creator><![CDATA[Jose Clemente García Rodríguez]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 17:07:40 GMT</pubDate>
            <atom:updated>2024-02-29T10:28:22.524Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular Data Binding — What is it?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7s0OkHnN2tqD3AbqVGCvg.jpeg" /></figure><p>Binding data is a fundamental part of web application development with Angular because it provides a powerful mechanism for exchanging information between the component class and the HTML view that defines the DOM.</p><p>This feature allows for building dynamic and interactive applications while automatically keeping the data synchronized in <em>one </em>or <em>two </em>directions.</p><h4>One-way binding</h4><p>One-way data binding entails the concept of linking data solely from the component class to the view or vice versa. This is particularly useful when we need to display static information on the screen, for example.</p><p><strong>Binding from the class to the view</strong></p><ul><li>Interpolation: the value of a property or the result of an expression will be dynamically inserted into a specific place in the HTML when it is rendered. To do this, we include the name of a property or expression within double curly braces ‘{{ }}’:</li></ul><pre>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;h1&gt;Hi, {{ name }}&lt;/h1&gt;<br>    &lt;h2&gt;{{ 2 + 2}}&lt;/h2&gt;<br>    &lt;h3&gt;{{ getText() }}&lt;/h3&gt;<br>  `<br>})<br>export class AppComponent {<br>  name: string = &#39;Jose&#39;;<br><br>  getText(): string {<br>    return &#39;Main text&#39;;<br>  }<br>}</pre><p>Obviously, each interpolated property or expression <strong>must exist</strong> in the component class.</p><p>Property / attribute / class / style: using the same logic as interpolation, we dynamically assign values to properties and attributes of HTML elements, but using square brackets ‘[]’ instead of double curly braces. 👆 In Angular, square brackets always indicate binding <strong>from the class to the view</strong>:</p><pre>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;div [class]=&quot;customClass&quot;&gt;<br>      &lt;h1 [innerHTML]=&quot;title&quot;&gt;&lt;/h1&gt;<br>      &lt;input [value]=&quot;mainValue&quot; [placeholder]=&quot;placeholder&quot; [style.color]=&quot;color&quot;&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class AppComponent {<br>  customClass: string = &#39;d-flex&#39;;<br>  title: string = &#39;Main title&#39;;<br>  mainValue: string = &#39;Main value&#39;;<br>  placeholder: string = &#39;Write me&#39;;<br>  color: string = &#39;blue&#39;;<br>}</pre><p><strong>Binding from the view to the class</strong></p><p>To bind data from the view to the class, we use Angular’s event binding, which allows us to listen for and respond to user actions. The syntax consists of an event name within parentheses and a statement. For example:</p><pre>&lt;button (click)=&quot;onClick()&quot;&gt;Click here!&lt;/button&gt;</pre><p>When the user clicks the button, the <em>onClick()</em> method of the component class will be called, which in turn executes the statement or set of statements we define (similar to adding event listeners in vanilla JavaScript). 👆 In Angular, parentheses always indicate binding <strong>from the view to the class</strong>.</p><p>It is also true that <em>data binding</em> involves linking data, and when we call a method from the view to the class (in this one-way binding), we are not strictly binding data in the traditional sense. Instead, we are establishing a “connection” between the view and the class, giving a broader meaning to the concept of <em>data binding</em>.</p><h4><strong>Two-way binding</strong></h4><p>Two-way data binding allows data to flow in both directions: from the class to the view and from the view to the class.</p><p>The most typical scenario for this case occurs when we use the <strong><em>NgModel </em></strong>directive when creating forms in Angular using <em>@angular/forms</em>. This is where we expect a user to input data.</p><pre>&lt;input [(ngModel)]=&quot;name&quot; placeholder=&quot;Write your name&quot;&gt;</pre><p>In the above code, two-way binding is established between the <em>name </em>property in the class and <em>the value of the input</em>. When the user enters a value in the input, the property value will automatically update with that value. Similarly, if the property is updated in the class, the input value will also update.</p><p>In this case, the concept of <em>data binding</em> through event binding makes more sense, as there is a strict binding of data and not just method calls.</p><h4><strong>Conclusion</strong></h4><p>We have just seen two essential and very useful ways to make information flow between the class and view of a component.</p><p>Additionally, it’s important to note that Angular has the ability to detect and prevent, for example, infinite loops of data updates, making this process highly efficient.</p><p>I hope this guide has been helpful to you.</p><p>Thank you very much for reaching this point.</p><h3>Love My Work? Here is How to Support Me!</h3><p><a href="https://www.buymeacoffee.com/m4n50n">Jose Clemente García Rodríguez</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d7c8a93a1c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Data Binding — ¿Qué es?]]></title>
            <link>https://medium.com/@joseclementegarciarodriguez/dominando-el-data-binding-en-angular-3c2556524111?source=rss-eca6a7f28806------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c2556524111</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[data-binding]]></category>
            <category><![CDATA[event-binding]]></category>
            <dc:creator><![CDATA[Jose Clemente García Rodríguez]]></dc:creator>
            <pubDate>Sat, 10 Jun 2023 21:39:33 GMT</pubDate>
            <atom:updated>2023-06-12T17:03:56.459Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7s0OkHnN2tqD3AbqVGCvg.jpeg" /></figure><p>Vincular o enlazar datos es una parte fundamental en el desarrollo de aplicaciones web con Angular, ya que nos proporciona un mecanismo muy poderoso de intercambio de información entre la clase del componente y la vista HTML que define el DOM.</p><p>Esta característica permitirá construir aplicaciones dinámicas e interactivas manteniendo los datos sincronizados automáticamente en <em>una </em>o <em>dos </em>direcciones.</p><h4><strong>Enlace unidireccional (One-way binding)</strong></h4><p>En enlace de datos en una sola dirección conforma la idea de vincular datos únicamente desde la clase del componente a la vista o viceversa. Esto nos será muy útil cuando necesitemos mostrar información estática por pantalla, por ejemplo.</p><p><strong>Enlazando desde la clase a la vista</strong></p><ul><li>Interpolación: se insertará dinámicamente el valor de una propiedad o resultado de una expresión en un lugar específico del HTML cuando este se renderice. Para ello incluiremos el nombre de una propiedad o expresión dentro de llaves dobles ‘{{ }}’:</li></ul><pre>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;h1&gt;Hola, {{ nombre }}&lt;/h1&gt;<br>    &lt;h2&gt;{{ 2 + 2}}&lt;/h2&gt;<br>    &lt;h3&gt;{{ getTexto() }}&lt;/h3&gt;<br>  `<br>})<br>export class AppComponent {<br>  nombre: string = &#39;Jose&#39;;<br><br>  getTexto(): string {<br>    return &#39;Texto de ejemplo&#39;;<br>  }<br>}</pre><p>Obviamente cada propiedad o expresión interpolada <strong>debe existir</strong> en la clase del componente.</p><ul><li>Propiedad / atributo / clase / estilo: usando la misma lógica que en la interpolación, asignaremos dinámicamente valores a propiedades y atributos de elementos HTML pero usando corchetes ‘[ ]’ en lugar de llaves dobles. 👆 En Angular, los corchetes siempre indicarán una vinculación <strong>desde la clase a la vista</strong>:</li></ul><pre>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;div [class]=&quot;clase&quot;&gt;<br>      &lt;h1 [innerHTML]=&quot;titulo&quot;&gt;&lt;/h1&gt;<br>      &lt;input [value]=&quot;valor&quot; [placeholder]=&quot;placeholder&quot; [style.color]=&quot;color&quot;&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class AppComponent {<br>  clase: string = &#39;d-flex&#39;;<br>  titulo: string = &#39;Título de ejemplo&#39;;<br>  valor: string = &#39;Valor de ejemplo&#39;;<br>  placeholder: string = &#39;Escribe un valor&#39;;<br>  color: string = &#39;blue&#39;;<br>}</pre><p><strong>Enlazando desde la vista a la clase</strong></p><p>Para vincular datos desde la vista a la clase usaremos el enlace de eventos de Angular, el cual permite escuchar y responder a acciones del usuario. La sintaxis consta de un nombre de evento entre paréntesis y una instrucción. Por ejemplo:</p><pre>&lt;button (click)=&quot;onClick()&quot;&gt;Haz click aquí!&lt;/button&gt;</pre><p>Cuando el usuario haga click sobre el botón se llamará al método <em>onClick()</em> de la clase del componente, que a su vez ejecutará la instrucción o conjunto de instrucciones que definamos (sí, de forma similar a cuando agregamos <em>listeners </em>de eventos en vanilla JavaScript). 👆 En Angular, los paréntesis siempre indicarán una vinculación <strong>desde la vista a la clase</strong>.</p><p>También es cierto que <em>data binding</em> implica la vinculación de datos, y cuando llamamos a un método de la clase desde la vista (en este enlace unidireccional) en realidad no estamos vinculando datos en el sentido estricto, sino que más bien establecemos una “conexión” entre la vista y clase, dando un significado más amplio al concepto de <em>data binding</em>.</p><h4>Enlace bidireccional (Two-way binding)</h4><p>El enlace de datos en dos direcciones permite que los datos fluyan en ambos sentidos: de la clase a la vista y de la vista a la clase.</p><p>El escenario más típico para este caso se presenta cuando usamos la directiva <strong><em>NgModel</em></strong> a la hora de crear formularios en Angular mediante <em>@angular/forms</em>, donde se espera que un usuario introduzca datos.</p><pre>&lt;input [(ngModel)]=&quot;nombre&quot; placeholder=&quot;Escribe tu nombre&quot;&gt;</pre><p>En el código anterior se establece la vinculación bidireccional entre la propiedad <em>nombre </em>en la clase y el <em>valor del input</em>: cuando el usuario escriba un valor en el input, el valor de la propiedad se actualizará con dicho valor automáticamente. Del mismo modo, si se actualiza la propiedad en la clase, el valor del input también lo hará.</p><p>En este caso cobra más sentido el concepto <em>data binding</em> enlazando eventos, ya que aquí sí que existe una vinculación estricta de datos y no solo llamadas a métodos.</p><h4><strong>Conclusión</strong></h4><p>Acabamos de ver dos maneras esenciales y muy útiles de conseguir que la información fluya entre clase y vista de un componente.</p><p>Además, debemos tener en cuenta que Angular tiene la capacidad de detectar y prevenir, por ejemplo, bucles infinitos de actualización de datos, por lo que consigue que este proceso se realice de una forma totalmente eficiente.</p><p>Espero que esta guía te haya sido de utilidad.</p><p>Muchas gracias por llegar hasta aquí.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c2556524111" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>