<?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 Ismaile ABDALLAH on Medium]]></title>
        <description><![CDATA[Stories by Ismaile ABDALLAH on Medium]]></description>
        <link>https://medium.com/@ZeroCool001?source=rss-6e921b69bd28------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yPr-iuJ4eQsjQV_14RIPUA@2x.jpeg</url>
            <title>Stories by Ismaile ABDALLAH on Medium</title>
            <link>https://medium.com/@ZeroCool001?source=rss-6e921b69bd28------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 12:16:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ZeroCool001/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[️ Hexagonal Architecture in Symfony: A Practical Guide to Layer Separation and Event-Driven…]]></title>
            <link>https://medium.com/@ZeroCool001/%EF%B8%8F-hexagonal-architecture-in-symfony-a-practical-guide-to-layer-separation-and-event-driven-d23d55a560c1?source=rss-6e921b69bd28------2</link>
            <guid isPermaLink="false">https://medium.com/p/d23d55a560c1</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[symfony]]></category>
            <dc:creator><![CDATA[Ismaile ABDALLAH]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 17:14:04 GMT</pubDate>
            <atom:updated>2026-03-31T17:14:04.955Z</atom:updated>
            <content:encoded><![CDATA[<h2>🏗️ Hexagonal Architecture in Symfony: A Practical Guide to Layer Separation and Event-Driven Design</h2><p><em>From MVC spaghetti to clean boundaries — a practical guide with Symfony Messenger and DDD patterns.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hVotMlhZWVAnk4py" /><figcaption>Photo by <a href="https://unsplash.com/@dalleng?utm_source=medium&amp;utm_medium=referral">Diego Allen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>🤓</em>A human architect designed this backend. Then an <em>🤖 </em>AI wrote the article about it. Ironic, no ?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irA6FfROe-OXQ2Cb4dEhAQ@2x.jpeg" /><figcaption>Photo by <a href="https://linktr.ee/omilaev">Igor Omilaev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Most Symfony projects start the same way: controllers, entities, services — the classic MVC triad. It works, until it doesn’t. As business logic grows, services become god classes, controllers leak domain rules, and testing anything in isolation feels like pulling teeth.</p><p>This article walks through how we structured a real-world Symfony 7 application using <strong>Hexagonal Architecture</strong> (Ports &amp; Adapters) combined with <strong>Event-Driven Architecture</strong>. Not as academic theory, but as a practical codebase that handles orders, inventory, notifications, and background jobs — all while keeping each concern cleanly separated.</p><h2>🚨 The Problem with Traditional Layering</h2><p>In a standard Symfony app, the dependency graph usually looks like this: Controllers depend on Services, which depend on Repositories, which depend on Doctrine. Everything points inward toward the framework. Need to swap your mailer? Good luck — it’s wired into six different services. Want to test business logic without a database? You’ll be mocking half the container.</p><p>Hexagonal Architecture flips this. The domain sits at the center, depending on nothing. The framework — Symfony, Doctrine, Stripe, any external service — lives at the edges, plugging into interfaces the domain defines. The result: business logic you can reason about, test, and evolve independently of infrastructure decisions.</p><h2>🔷 Hexagonal Architecture in Practice</h2><p>⚠️ <strong>There is no single “right” way to implement Hexagonal Architecture.</strong></p><p>Every feature in our codebase follows a three-layer structure. Here’s what the Product feature looks like:</p><pre>Product/<br>├── CreateProduct/<br>│   ├── Domain/<br>│   │   ├── Command/<br>│   │   │   ├── CreateProduct.php<br>│   │   │   └── CreateProductHandler.php<br>│   │   ├── Exception/<br>│   │   │   └── InvalidProductException.php<br>│   └── UserInterface/<br>│       └── Http/<br>│           ├── CreateProductController.php<br>│           └── Dto/<br>│               └── CreateProductDto.php<br>├── ListProduct/<br>│   ├── Domain/<br>│   │   └── Query/<br>│   │       ├── ListProduct.php<br>│   │       └── ListProductHandler.php<br>│   └── UserInterface/<br>│       └── Http/<br>│           ├── ListProductController.php<br>│           └── Model/<br>│               ├── ProductResponse.php<br>│               └── ProductsResponse.php<br>└── Shared/<br>    ├── Domain/<br>    │   └── Storage/<br>    │       └── ProductStorageInterface.php<br>    └── Infrastructure/<br>        └── Storage/<br>            ├── S3ProductStorage.php<br>            └── InMemoryProductStorage.php</pre><p>Three layers, three responsibilities:</p><ul><li><strong>Domain/</strong> — Business logic, commands, queries, events, repository interfaces. Zero framework imports. This is the core that everything else orbits.</li><li><strong>UserInterface/</strong> — HTTP controllers, CLI commands, request DTOs with validation. This is the “driving” side — how the outside world talks to the domain.</li><li><strong>Infrastructure/</strong> — Doctrine repositories, S3 adapters, email engines. This is the “driven” side — how the domain talks to the outside world, through interfaces it defines.</li></ul><p>The key insight: Domain/Repository/ProductRepositoryInterface.php is an interface defined <em>by</em> the domain. The Doctrine implementation lives in Infrastructure. The domain never knows Doctrine exists. Want to swap to MongoDB? Write a new adapter, change one line of config.</p><h2>✂️ CQRS: Separating Reads from Writes</h2><p>Every operation in the system is either a <strong>Command</strong> (write) or a <strong>Query</strong> (read). They travel through separate buses with different middleware stacks.</p><h3>✏️ Commands: Where State Changes Happen</h3><p>A command is a simple, immutable value object:</p><pre>final readonly class CancelOrder<br>{<br>    public function __construct(<br>        public int $orderId,<br>        public string $reason,<br>    ) {<br>    }<br>}</pre><p>Its handler extends AbstractCommandHandler and does the actual work:</p><pre>final class CancelOrderHandler extends AbstractCommandHandler<br>{<br>    public function __construct(<br>        private readonly OrderRepositoryInterface $orderRepository,<br>        private readonly EventBus $eventBus,<br>    ) {<br>    }<br><br>    public function __invoke(CancelOrder $request): void<br>    {<br>        $order = $this-&gt;orderRepository-&gt;findOneById($request-&gt;orderId);<br>        $order-&gt;cancel($request-&gt;reason);<br>        $this-&gt;orderRepository-&gt;save($order);<br>        <br>        $this-&gt;eventBus-&gt;raise(<br>            new OrderCancelled($order-&gt;getId())<br>        );<br>    }<br>}</pre><p>Notice: the handler depends on OrderRepositoryInterface, not OrderRepository. It raises a domain event, not an email. It knows <em>what</em> happened, not <em>what should happen next</em>. That&#39;s the separation doing its job.</p><h3>🎛️ Controllers: Thin by Design</h3><p>Controllers do one thing — translate HTTP into bus calls:</p><pre>#[Route(&#39;/products&#39;, methods: [&#39;GET&#39;])]<br>final class ListProductController extends AbstractController<br>{<br>    public function __invoke(<br>        QueryBus $queryBus,<br>        JsonResponder $jsonResponder,<br>    ): JsonResponse {<br>        $result = $queryBus-&gt;query(new ListProduct());<br>        return $jsonResponder-&gt;response($result);<br>    }<br>}</pre><p>Three lines of logic. No business rules. No data transformation. If you’re reading a controller and it’s longer than 20 lines, something domain-level has leaked into the wrong layer.</p><h2>⚡ Event-Driven Architecture: Decoupling Side Effects</h2><p>This is where the architecture really pays off. When an order is cancelled, the system needs to:</p><ol><li>Notify the admin by email</li><li>Send a confirmation email to the customer</li><li>Trigger an inventory restock</li></ol><p>None of these belong in the CancelOrderHandler. They&#39;re side effects — important, but not the core operation. The handler raises one event and moves on:</p><pre>$this-&gt;eventBus-&gt;raise(new OrderCancelled($order-&gt;getId()));</pre><h3>🕐 The EventBus: Deferred Dispatch</h3><p>Our EventBus implementation uses Symfony Messenger’s DispatchAfterCurrentBusStamp — a small but critical detail:</p><pre>final class EventBus<br>{<br>    public function __construct(private MessageBusInterface $eventBus)<br>    {<br>    }<br><br>    public function raise(object $event): void<br>        {<br>            $envelope = (new Envelope($event))<br>                -&gt;with(new DispatchAfterCurrentBusStamp());<br>           <br>             $this-&gt;eventBus-&gt;dispatch($envelope);<br>        }<br>    }<br>}</pre><p>The DispatchAfterCurrentBusStamp ensures events are dispatched <strong>after</strong> the current command bus finishes — including the Doctrine transaction commit. This means event handlers will never see uncommitted state. If the transaction rolls back, the events simply never fire.</p><h3>🎯 Event Handlers: One Event, Many Reactions</h3><p>Each side effect gets its own handler:</p><pre>final class NotifyAdminOnOrderCancelledHandler implements EventHandler<br>{<br>    public function __construct(<br>        private readonly EmailSenderEngine $emailSenderEngine,<br>        private readonly Environment $twig,<br>        private readonly string $adminEmail,<br>    ) {<br>    }<br>  <br>    public function __invoke(OrderCancelled $event): void<br>    {<br>        $email = $this-&gt;twig-&gt;render(<br>            &#39;emails/NotifyAdminOrderCancelled/email.html.twig&#39;,<br>            [&#39;order_id&#39; =&gt; $event-&gt;orderId]<br>        );<br>        $this-&gt;emailSenderEngine-&gt;send(<br>            [$this-&gt;adminEmail],<br>            &#39;Notification: An order has been cancelled&#39;,<br>            $email,<br>        );<br>    }<br>}</pre><p>And in a separate file, another handler reacts to the same event — but instead of performing writes directly, it dispatches a dedicated command:</p><pre>final class SendConfirmationToCustomerHandler implements EventHandler<br>{<br>    public function __construct(<br>        private readonly CommandBus $commandBus,<br>    ) {<br>    }<br>    <br>    public function __invoke(OrderCancelled $event): void<br>    {<br>        $this-&gt;commandBus-&gt;command(<br>            new SendCancellationConfirmation($event-&gt;orderId)<br>        );<br>    }<br>}</pre><p>This is a deliberate design choice: <strong>event handlers should never write to the database directly</strong>. An event handler’s job is to <em>react</em> and <em>coordinate</em> — not to own a write operation. If a side effect requires state changes (generating a refund token, updating a status), it dispatches a command that goes through the command bus with its own transaction, its own handler, and its own responsibility boundary.</p><p>The SendCancellationConfirmationHandler then owns the actual write:</p><pre>final class SendCancellationConfirmationHandler extends AbstractCommandHandler<br>{<br>    public function __invoke(SendCancellationConfirmation $command): void<br>    {<br>        $order = $this-&gt;orderRepository-&gt;findOneById($command-&gt;orderId);<br>        $customer = $order-&gt;getCustomer();<br>        <br>        $token = Ulid::generate();<br>        $customer-&gt;setRefundToken($token);<br>        $this-&gt;customerRepository-&gt;save($customer);<br>        $this-&gt;customerRepository-&gt;store();<br>        // Send email with refund tracking link...<br>    }<br>}</pre><p>This way, each write operation flows through the command bus — wrapped in a Doctrine transaction, properly isolated, and independently testable.</p><p>Both event handlers react to the same OrderCancelled event. Neither knows the other exists. Adding a third reaction — say, a webhook notification — means adding one new class. Zero changes to existing code. This is the Open/Closed Principle made tangible.</p><h2>🚀 Async Processing with Symfony Messenger</h2><p>Some operations are too slow or too risky for synchronous execution. Email sending, report generation, external API calls — these need to run in background workers.</p><p>Symfony Messenger handles this through transport routing in messenger.yaml:</p><pre>framework:<br>    messenger:<br>        transports:<br>            notification_queue:<br>                dsn: &#39;%env(MESSENGER_TRANSPORT_DSN)%&#39;<br>                retry_strategy:<br>                    max_retries: 3<br>                    delay: 1000<br>                    multiplier: 10<br>                options:<br>                    queue_name: notification_queue<br>            inventory_sync:<br>                dsn: &#39;%env(MESSENGER_TRANSPORT_DSN)%&#39;<br>                options:<br>                    queue_name: inventory_sync<br>        routing:<br>            &#39;App\...\SendNotification&#39;: notification_queue<br>            &#39;App\...\ConfirmShipment&#39;: notification_queue<br>            &#39;App\...\SyncInventory&#39;: inventory_sync<br>        buses:<br>            messenger.bus.command:<br>                middleware:<br>                    - doctrine_transaction<br>            messenger.bus.query: ~<br>            messenger.event.bus:<br>                default_middleware:<br>                    enabled: true<br>                    allow_no_handlers: true</pre><p>The beauty: the handler code doesn’t change whether a command runs sync or async. SyncInventory is dispatched exactly like any other command — Messenger&#39;s routing decides it goes to a queue instead of executing immediately.</p><p>Each queue gets its own Docker container as a dedicated worker, providing isolation and independent scaling.</p><h3>🧪 Testing Async Flows</h3><p>In tests, all transports switch to synchronous execution:</p><pre>when@test:<br>    framework:<br>        messenger:<br>            transports:<br>                notification_queue: &#39;sync://&#39;<br>                inventory_sync: &#39;sync://&#39;</pre><p>One config block. Every async flow becomes deterministically testable without touching the application code.</p><h2>🔌 Auto-Wiring It All Together</h2><p>The glue that makes this work without manual service registration is Symfony’s _instanceof feature in services.yaml:</p><pre>services:<br>    _instanceof:<br>        App\Shared\Domain\Handler\AbstractCommandHandler:<br>            tags:<br>                - { name: messenger.message_handler, bus: messenger.bus.command }<br>        App\Shared\Domain\Handler\AbstractQueryHandler:<br>            tags:<br>                - { name: messenger.message_handler, bus: messenger.bus.query }<br>        App\Shared\Domain\Handler\EventHandler:<br>            tags:<br>                - { name: messenger.message_handler, bus: messenger.event.bus }</pre><p>Every class extending AbstractCommandHandler is automatically registered on the command bus. Every class implementing EventHandler goes to the event bus. Add a new handler, and it just works — no config changes, no service definitions, no wiring files.</p><p>This is what makes the architecture scale. New features follow the established patterns, and the framework configuration catches up automatically. A developer adding a feature only needs to think about three things: what’s my command/query, what does my handler do, and what’s my response shape.</p><h2>🏆 What We Gained</h2><p>🧪 <strong>Testability</strong> — Domain handlers can be unit-tested with interface mocks. No database, no HTTP, no framework boot. Integration tests use Behat with real databases and sync:// transports for deterministic async testing.</p><p>🧭 <strong>Navigability</strong> — Finding code is trivial. “Where is product listing handled?” → src/Product/ListProduct/. Every feature is self-contained. There&#39;s no 2000-line ProductService to grep through.</p><p>🔄 <strong>Safe evolution</strong> — Adding a side effect to a domain event means a new handler class. Adding a new feature means a new directory. The architecture channels change into addition, not modification.</p><p>The upfront cost is real — more files, more directories, stricter conventions. But for a codebase that multiple developers touch over months and years, that structure isn’t overhead. It’s the thing that keeps velocity from collapsing.</p><p><em>The patterns shown here aren’t new — hexagonal architecture dates to 2005, CQRS to 2010. What’s valuable is seeing them applied together in a modern Symfony stack, not as architecture astronautics, but as practical tools for managing complexity in a real application.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d23d55a560c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⚡ Add Filters to Your Symfony API in 3 Minutes Flat]]></title>
            <link>https://medium.com/@ZeroCool001/add-filters-to-your-symfony-api-in-3-minutes-flat-35f1d3e71c05?source=rss-6e921b69bd28------2</link>
            <guid isPermaLink="false">https://medium.com/p/35f1d3e71c05</guid>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[symfony-bundle]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Ismaile ABDALLAH]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 21:00:42 GMT</pubDate>
            <atom:updated>2026-03-04T21:00:42.827Z</atom:updated>
            <content:encoded><![CDATA[<p>Stop writing the same filter for every endpoint. There’s a better way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cGRmio0E3BDIUFtk" /><figcaption>Photo by <a href="https://unsplash.com/@_3bread?utm_source=medium&amp;utm_medium=referral">sehoon ye</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>😩 The Problem We All Know Too Well</h3><p>You’re building a REST API with Symfony. Your client needs to filter users by name, status, age range, email domain… You know the drill.</p><p>So you start writing this:</p><pre>public function list(Request $request): JsonResponse<br>{<br>    $qb = $this-&gt;userRepository-&gt;createQueryBuilder(&#39;u&#39;);<br><br>    if ($request-&gt;query-&gt;has(&#39;firstname&#39;)) {<br>        $qb-&gt;andWhere(&#39;u.firstname = :firstname&#39;)<br>            -&gt;setParameter(&#39;firstname&#39;, $request-&gt;query-&gt;get(&#39;firstname&#39;));<br>    }<br><br>    if ($request-&gt;query-&gt;has(&#39;status&#39;)) {<br>        $qb-&gt;andWhere(&#39;u.status = :status&#39;)<br>            -&gt;setParameter(&#39;status&#39;, $request-&gt;query-&gt;get(&#39;status&#39;));<br>    }<br><br>    if ($request-&gt;query-&gt;has(&#39;min_age&#39;)) {<br>        $qb-&gt;andWhere(&#39;u.age &gt;= :min_age&#39;)<br>            -&gt;setParameter(&#39;min_age&#39;, $request-&gt;query-&gt;get(&#39;min_age&#39;));<br>    }<br><br>    // ... 50 more lines of this 😭<br>}</pre><p>For <strong>every. single. endpoint. </strong>Just copy-paste spaghetti that grows with every new requirement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mk64ucwdpfCNgU8HcC9A9Q.jpeg" /></figure><h3>🎯 What if You Could Do This Instead?</h3><pre>#[Route(&#39;/api/users&#39;, methods: [&#39;GET&#39;])]<br>#[ApiFilter(name: &#39;firstname&#39;, allowedTypes: [FilterType::Eq-&gt;value, FilterType::Like-&gt;value])]<br>#[ApiFilter(name: &#39;status&#39;, enumClass: UserStatus::class)]<br>#[ApiFilter(name: &#39;age&#39;, allowedTypes: [FilterType::Gte-&gt;value, FilterType::Lte-&gt;value])]<br>#[ApiFilter(name: &#39;deleted_at&#39;, allowedTypes: [FilterType::IsNull-&gt;value])]<br>public function list(Filters $filters): JsonResponse<br>{<br>    $users = $this-&gt;userRepository-&gt;findByFilters($filters);<br><br>    return $this-&gt;json($users);<br>}</pre><p><strong>That’s it.</strong> No manual parsing. No parameter binding. No validation code. Just declare what you allow, and the bundle handles the rest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*pAw559nK-JUcqcg3g3BC8w.gif" /></figure><h3>📦 Meet isma/api-filters-bundle</h3><p><a href="https://github.com/yagami271/api-filters-bundle"><strong>isma/api-filters-bundle</strong></a> is a Symfony bundle that:</p><ol><li>🏷️ <strong>Reads </strong>#[ApiFilter]<strong> attributes</strong> from your controller methods</li><li>✅ <strong>Parses &amp; validates</strong> query string filters automatically</li><li>🔧 <strong>Applies them to your Doctrine QueryBuilder.</strong></li></ol><p>It ships with multiple <strong>filters types</strong> and is fully extensible.</p><h3>🚀 Setup in 3 Minutes</h3><p><strong>Minute 1 — Install</strong></p><pre>composer require isma/api-filters-bundle</pre><p><strong>Minute 2 — Declare Your Filters</strong></p><p>Add #[ApiFilter] attributes to your controller action:</p><pre>use Isma\ApiFiltersBundle\Attribute\ApiFilter;<br>use Isma\ApiFiltersBundle\ValueObject\Filters;<br>use Isma\ApiFiltersBundle\ValueObject\FilterType;<br><br>final class ProductController<br>{<br>    #[Route(&#39;/api/products&#39;, methods: [&#39;GET&#39;])]<br>    #[ApiFilter(name: &#39;name&#39;, allowedTypes: [FilterType::Like-&gt;value, FilterType::StartWith-&gt;value])]<br>    #[ApiFilter(name: &#39;price&#39;, allowedTypes: [FilterType::Gte-&gt;value, FilterType::Lte-&gt;value])]<br>    #[ApiFilter(name: &#39;category&#39;, allowedTypes: [FilterType::Eq-&gt;value])]<br>    #[ApiFilter(name: &#39;discontinued_at&#39;, allowedTypes: [FilterType::IsNull-&gt;value])]<br>    public function list(Filters $filters): JsonResponse<br>    {<br>        // $filters is automatically resolved from the query string 🪄<br>    }<br>}</pre><p>The Filters object is injected via Symfony&#39;s ValueResolverInterface — no manual Request parsing needed.</p><p><strong>Minute 3 — Apply to Your Query</strong></p><pre>use Isma\ApiFiltersBundle\Filter\FilterApplierInterface;<br><br>final class ProductRepository<br>{<br>    public function __construct(<br>        private FilterApplierInterface $filterApplier,<br>    ) {}<br><br>    public function findByFilters(Filters $filters): array<br>    {<br>        $qb = $this-&gt;createQueryBuilder(&#39;p&#39;);<br><br>        $this-&gt;filterApplier-&gt;apply($qb, $filters, [<br>            &#39;name&#39;             =&gt; &#39;p.name&#39;,<br>            &#39;price&#39;            =&gt; &#39;p.price&#39;,<br>            &#39;category&#39;         =&gt; &#39;p.category&#39;,<br>            &#39;discontinued_at&#39;  =&gt; &#39;p.discontinuedAt&#39;,<br>        ]);<br><br>        return $qb-&gt;getQuery()-&gt;getResult();<br>    }<br>}</pre><p>The mapping array (&#39;name&#39; =&gt; &#39;p.name&#39;) connects the public filter names from the URL to your actual Doctrine columns. That&#39;s your security layer — only mapped fields can be filtered.</p><p><strong>Now hit your API:</strong></p><pre>GET /api/products?filters[name][like]=keyboard<br>GET /api/products?filters[price][gte]=50&amp;filters[price][lte]=200<br>GET /api/products?filters[category][eq]=electronics</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*eWN_ZkyoZ1aVpgZLpLdp6Q.gif" /></figure><p>⏱️ Three minutes. No extra code. Completely validated.</p><p>Each filter type lives in its own class. Want to add an x-between filter? Simply create it:</p><pre>use Doctrine\ORM\QueryBuilder;<br>use Isma\ApiFiltersBundle\Filter\FilterStrategyInterface;<br><br>final class BetweenFilterStrategy implements FilterStrategyInterface<br>{<br>    public function getType(): string<br>    {<br>        return &#39;x-between&#39;;<br>    }<br><br>    public function apply(<br>        QueryBuilder $queryBuilder,<br>        string $column,<br>        mixed $value,<br>        string $parameterName,<br>    ): void {<br>        $queryBuilder<br>            -&gt;andWhere(sprintf(<br>                &#39;%s BETWEEN :%s_min AND :%s_max&#39;,<br>                $column,<br>                $parameterName,<br>                $parameterName,<br>            ))<br>            -&gt;setParameter($parameterName . &#39;_min&#39;, $value[0])<br>            -&gt;setParameter($parameterName . &#39;_max&#39;, $value[1]);<br>    }<br>}</pre><p>That’s all.<br>✅ No service registration. <br>✅ No YAML.<br>✅ No XML.</p><p>It’s automatically discovered via Symfony autoconfiguration.</p><p>Example request:</p><pre>GET /api/products?filters[price][x-between][]=100&amp;filters[price][x-between][]=500</pre><h3>✍️ Conclusion</h3><p>If you’re building a custom API with Symfony and don’t need the full API Platform ecosystem, this bundle is for you. Lightweight, declarative, and free from unnecessary complexity — just filtering, nothing more.</p><p>The project is open source and contributions are welcome. Whether it’s a new filter, a bug fix, or an improvement idea, feel free to open an issue or submit a PR on GitHub. Every contribution matters.</p><p><em>If this article helped you, give it a 👏 and follow me for more Symfony tips!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35f1d3e71c05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Create your first custom Phpstan rule]]></title>
            <link>https://medium.com/@ZeroCool001/create-your-first-custom-phpstan-rule-385bf98df21d?source=rss-6e921b69bd28------2</link>
            <guid isPermaLink="false">https://medium.com/p/385bf98df21d</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[phpstan]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[symfony]]></category>
            <dc:creator><![CDATA[Ismaile ABDALLAH]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 09:07:02 GMT</pubDate>
            <atom:updated>2025-11-16T09:07:02.409Z</atom:updated>
            <content:encoded><![CDATA[<p>“Stop Writing ADRs, Start Writing Phpstan Rules”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YSR3NSJpgdRaWcVR" /><figcaption>Photo by <a href="https://unsplash.com/@heyjamaal?utm_source=medium&amp;utm_medium=referral">Jamaal Kareem</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>ℹ️ Before diving directly in to code, let talk about the AST</h4><p>When PHPStan analyzes a PHP file, the first step is <strong>parsing, </strong>converting the raw PHP source code into a structured tree that represents the syntax and semantics of your code.<br>This tree-like structure is called the <strong>Abstract Syntax Tree (AST)</strong>.</p><p>Consider AST as a tree 🎄 of your code, where each element (class, method, variable, function call, etc.) is represented by a node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yVwRjQBHVholAltngmyDw.png" /><figcaption><a href="https://ruslanspivak.com/lsbasi-part7/">https://ruslanspivak.com/lsbasi-part7/</a></figcaption></figure><p>🏛️ Let’s take a real-world example: we want to <strong>standardize all our enums</strong> across the project.<br>We’ve decided that every enum <strong>case name</strong> should use <strong>UPPER_SNAKE_CASE</strong>, while the <strong>case value</strong> should use <strong>lower_snake_case</strong>.</p><pre>&lt;?php<br><br>enum MyEnum: string<br>{<br>    case foo = &#39;FOO&#39;; // Doesn&#39;t respect ADR<br><br>    case FooBar = &#39;FOO_BAR&#39;; // Doesn&#39;t respect ADR<br><br>    case Yolo = &#39;Yolo&#39;; // Doesn&#39;t respect ADR<br>}</pre><p>Instead of writing an ADR (Architecture Decision Record) and asking everyone to remember the rule during code reviews, we can create a <strong>PHPStan custom rule</strong> to enforce it automatically. That way, you can save your time and energy for more important things during PR reviews.</p><h4>💡 Tips</h4><p>When I first tried writing a custom PHPStan rule, the very first question that hit me was:<br><strong>“How do I even know which node my rule should target?” 😢</strong></p><p>Don’t worry ! If you’re a noob like me, there’s an easy trick!<br>You can use <a href="https://getrector.com/ast/">https://getrector.com/ast/</a> to play around with your PHP code and instantly see the <strong>AST node structure </strong>you’ll need for your rule.<br>It’s like a cheat sheet for discovering the exact node type 🪄</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*glPr-mRmqs5Sl3hTlRQMfA.gif" /><figcaption><a href="https://getrector.com/ast">https://getrector.com/ast</a></figcaption></figure><p>🪄 As you can see, we easily identified the <strong>AST</strong> node <strong>EnumCase</strong>, where our new rule will be applied.</p><h3>✍️ Let’s start by creating our first rule for enum case</h3><pre>&lt;?php<br><br>/**<br> * @implements Rule&lt;EnumCase&gt;<br> */<br>final class EnumClassRule implements Rule<br>{<br>    public function getNodeType(): string<br>    {<br>        return EnumCase::class;<br>    }<br><br>    public function processNode(Node $node, Scope $scope): array<br>    {<br>        // Your logic <br>       <br>    }<br>}</pre><p>⚠️ Three Key Steps to Create Your PHPStan Rule</p><ol><li>Implement the PHPStan\Rules\Rule interface</li><li>Implement <strong>getNodeType()</strong> in order to return the AST node where to apply Your Rule.. For our case we will return <strong>PhpParser\Node\Stmt\EnumCase::class</strong></li><li>Add the annotation<strong> @implements Rule&lt;EnumCase&gt;</strong></li></ol><p>Now, let’s implement ProcessNode logic too !</p><pre>&lt;?php<br><br>public function processNode(Node $node, Scope $scope): array<br>    {<br>        $errors = [];<br>        if (!preg_match(&#39;/^[A-Z0-9_]+$/&#39;, $node-&gt;name-&gt;toString())) {<br>            $errors[] = RuleErrorBuilder::message(sprintf(<br>                &#39;Enum case &quot;%s&quot; must be in UPPER_SNAKE_CASE.&#39;,<br>                $node-&gt;name-&gt;toString()))<br>                -&gt;identifier(&#39;rule.enumCaseUpperSnakeCase&#39;)<br>                -&gt;build();<br>        }<br><br>        $expr = $node-&gt;expr;<br>        if ($expr instanceof String_ &amp;&amp; !preg_match(&#39;/^[a-z0-9_]+$/&#39;, $expr-&gt;value)) {<br>            $errors[] = RuleErrorBuilder::message(sprintf(<br>                &#39;Enum value &quot;%s&quot; must be in lower_snake_case.&#39;,<br>                $expr-&gt;value))<br>                -&gt;identifier(&#39;rule.enumValueLowerSnakeCase&#39;)<br>                -&gt;build();<br>        }<br><br>        return $errors;<br>    }</pre><h4>💡 Tips:</h4><p>⚠️ Don’t forget to register your rule in your phpstan.neon file:</p><pre>parameters:<br>    level: max<br>    paths:<br>        - src/<br><br>rules:<br>    - FirstRule\PhpStan\Rules\EnumClassRule</pre><p>Then, run PHPStan in debug mode to see your rule in action:</p><pre>./vendor/bin/phpstan --debug <br><br> Line   Fixtures/MyEnum.php                                <br> ------ --------------------------------------------------- <br>  7      Enum case &quot;foo&quot; must be in UPPER_SNAKE_CASE.       <br>         🪪  rule.enumCaseUpperSnakeCase                    <br>         at src/Fixtures/MyEnum.php:7                       <br>  7      Enum value &quot;FOO&quot; must be in lower_snake_case.      <br>         🪪  rule.enumValueLowerSnakeCase                   <br>         at src/Fixtures/MyEnum.php:7                       <br>  10     Enum case &quot;FooBar&quot; must be in UPPER_SNAKE_CASE.    <br>         🪪  rule.enumCaseUpperSnakeCase                    <br>         at src/Fixtures/MyEnum.php:10                      <br>  10     Enum value &quot;FOO_BAR&quot; must be in lower_snake_case.  <br>         🪪  rule.enumValueLowerSnakeCase                   <br>         at src/Fixtures/MyEnum.php:10                      <br>  13     Enum case &quot;Yolo&quot; must be in UPPER_SNAKE_CASE.      <br>         🪪  rule.enumCaseUpperSnakeCase                    <br>         at src/Fixtures/MyEnum.php:13                      <br>  13     Enum value &quot;Yolo&quot; must be in lower_snake_case.     <br>         🪪  rule.enumValueLowerSnakeCase                   <br>         at src/Fixtures/MyEnum.php:13</pre><p>🎉 <strong>Bravo!</strong> You’ve just created your first PHPStan custom rule.<br>Now, your codebase automatically enforces the decisions your team made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*i872oxHmKup5187RQhDD7Q.gif" /></figure><p>So go ahead ! <strong>Free your mind</strong> and start creating your own custom rules!<br>Let PHPStan enforce your standards, while you focus on what really matters: building great features. 🚀</p><h3>🧠 To summarise</h3><p>If you find yourself repeating the same comment during code reviews</p><ul><li>“Don’t use that function here”</li><li>“Name this properly”</li><li>“Follow this convention…”</li></ul><p>That’s your cue.<br><strong>Automate it with a PHPStan rule and free your mind for real engineering.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=385bf98df21d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Les erreurs à éviter lorsque l’on change d’entreprise en tant que développeuse ou développeur]]></title>
            <link>https://medium.com/@ZeroCool001/les-erreurs-%C3%A0-%C3%A9viter-lorsque-lon-change-d-entreprise-en-tant-que-d%C3%A9veloppeuse-ou-d%C3%A9veloppeur-28019a5db80d?source=rss-6e921b69bd28------2</link>
            <guid isPermaLink="false">https://medium.com/p/28019a5db80d</guid>
            <category><![CDATA[social-enterprise]]></category>
            <category><![CDATA[social-skills]]></category>
            <category><![CDATA[soft-skill-training]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[change]]></category>
            <dc:creator><![CDATA[Ismaile ABDALLAH]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 10:54:19 GMT</pubDate>
            <atom:updated>2024-11-24T10:54:19.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pZKetxaYzh2-2YVH" /><figcaption>Photo by <a href="https://unsplash.com/@m4quuv?utm_source=medium&amp;utm_medium=referral">Piotr Makowski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Dans une partie d’échecs, il est tentant de vouloir imposer rapidement son style de jeu. Pourtant, les meilleurs joueurs savent que précipiter les choses mène souvent à la défaite. Il faut d’abord observer, analyser les mouvements de l’autre et comprendre le terrain avant d’élaborer sa stratégie. Arriver dans une nouvelle entreprise en tant que développeuse ou développeur, c’est un peu comme entamer une nouvelle partie d’échecs. Vouloir reproduire immédiatement ce qui fonctionnait dans vos anciennes expériences peut être aussi risqué que de lancer une attaque trop tôt aux échecs.</p><p>Dans cet article, je vous partage les pièges à éviter lorsque l’on change d’entreprise qu’on soit développeur ou autre.</p><p>il n’est pas rare de rencontrer des collaboratrices ou collaborateurs qui, à peine arrivés dans une nouvelle entreprise, veulent tout révolutionner, ou vite recréer le confort dont ils jouissaient dans leur précédente entreprise. Cela peut prendre plusieurs formes comme :</p><ol><li>Appliquer immédiatement des pratiques ou des méthodologies de leur ancienne structure, sans tenir compte du contexte actuel</li><li>Proposer de refondre l’architecture logicielle dès les premier mois, souvent sans avoir pris le temps de comprendre pourquoi elle a été conçue de cette manière</li><li>Critiquer le code existant, qualifiant souvent certaines parties de “mal conçues” avant même d’avoir discuté avec les équipes en place</li><li>Critiquer sans justification claire et nette qui permettrait de tendre vers une solution</li><li>Ne pas vouloir comprendre ou donner une chance à l’architecture/méthodologie existante, car pour vous elle est mal conçue, et par conséquent ça ne sert à rien de continuer à l’utiliser</li></ol><p>Bien que cette attitude est souvent motivée par de bonnes intentions, cela peut générer du rejet et créer une mauvaise dynamique au sein de l’équipe. Non seulement elle risque de frustrer les collaboratrices et collaborateurs, mais elle peut également isoler la nouvelle personne arrivée, perçue comme quelqu’un de critique.</p><p>Il est naturel de vouloir apporter des améliorations. Après tout, si vous êtes embauché(e) dans une nouvelle entreprise, c’est aussi pour contribuer à sa croissance et à son amélioration. Cependant, il est essentiel de le faire avec bienveillance et de manière progressive. Voici quelques conseils :</p><h4>1. Patientez, observez et imitez</h4><p>Prenez le temps d’observer comment l’équipe actuelle fonctionne. Codez comme les autres membres de l’équipe, même si des éléments ne semblent pas figurer dans les bonnes pratiques.. En vous donnant du temps, vous pourrez mieux comprendre les dynamiques internes et identifier de manière plus précise les vrais points d’amélioration.</p><h3>2. Laissez derrière vous vos anciennes habitudes</h3><p>L’une des erreurs courantes est de vouloir absolument reproduire ce qui fonctionnait dans vos expériences précédentes. Cela peut être des outils, des méthodes de travail ou même des processus de développement. Chaque entreprise a ses particularités, et il est important de ne pas essayer de transposer directement des pratiques sans les adapter au nouveau contexte.</p><h3>3. Introduisez des nouveautés progressivement</h3><p>Si vous pensez qu’une amélioration peut vraiment bénéficier à l’équipe, proposez-la de manière progressive. Testez-la sur un petit projet, faites une preuve de concept ou parlez-en avec les membres de l’équipe pour avoir leur retour. Les changements trop rapides peuvent être source de stress pour une équipe qui a ses habitudes. Il est donc crucial d’introduire des nouveautés de manière douce et mesurée.</p><h3>4. Apprenez à ne pas choquer</h3><p>Chaque entreprise a sa culture, son histoire et ses manières de faire. Ce qui peut vous sembler déroutant ou inefficace à première vue a souvent une raison d’être. Au lieu de dire « Ce n’est pas comme ça qu’on fait », préférez une approche plus ouverte en cherchant à comprendre avant de proposer des alternatives. En évitant de choquer ou de vous positionner comme le « sauveur » qui va tout changer, vous gagnez la confiance de l’équipe et vous vous intégrez plus facilement.</p><h3>5. Mettre en place une conduite du changement :</h3><ul><li><strong>Identification des motivations</strong> <strong>: </strong>poser vous la question pourquoi changer ? Il est crucial de justifier le changement et éviter de changer un élément juste par caprice ou challenge technique personnel</li><li><strong>Vision claire et bonne communication : </strong>communiquer une vision claire à toute l’équipe, expliquer ce que ce changement va apporter</li><li><strong>Formation et montée au compétence : </strong>accompagner<strong> </strong>les collaboratrices, collaborateurs vers le changement, proposer une session de formation par exemple</li><li><strong>Anticiper les résistances : </strong>le changement de manière de coder et d’architecture logicielle peut provoquer des résistances, surtout chez les développeuses et développeurs expérimentés qui ont leurs habitudes. Il est important d’écouter leurs inquiétudes et d’expliquer pourquoi ces changements sont nécessaires de façon claire et argumentée.</li><li><strong>Déploiement progressif : </strong>élargir le changement progressivement, par exemple tester le changement sur un module ou deux avant de l’étendre au reste du projet</li><li><strong>Valorisation des succès : </strong>célébrer les premières victoires</li></ul><h3>Conclusion</h3><p>Changer d’entreprise en tant que développeuse ou développeur est un défi excitant, mais il faut être vigilant(e) à ne pas vouloir tout transformer dès le départ. Chaque structure a ses particularités, ses contraintes et son histoire, et il est essentiel de prendre le temps de les comprendre avant d’essayer d’y appliquer ses propres méthodes.</p><p>Soyez patient(e), observez, écoutez, et surtout, soyez bienveillant(e) dans votre approche du changement. L’innovation et l’amélioration, quand elles sont introduites avec douceur et dans un esprit de collaboration, sont beaucoup plus efficaces et bénéfiques pour l’équipe et l’entreprise dans son ensemble.</p><p><em>Crédits : merci à </em><a href="https://medium.com/u/3d5d5ad9c99d"><em>Gregory</em></a><em> pour la relecture et correction.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28019a5db80d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How PHP Generics Can Save You from Rewriting Doctrine Repositories]]></title>
            <link>https://medium.com/@ZeroCool001/how-php-generics-can-save-you-from-rewriting-doctrine-repositories-d217dd44f488?source=rss-6e921b69bd28------2</link>
            <guid isPermaLink="false">https://medium.com/p/d217dd44f488</guid>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[php-developers]]></category>
            <category><![CDATA[generic-programming]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Ismaile ABDALLAH]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 20:11:14 GMT</pubDate>
            <atom:updated>2024-10-20T20:11:14.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EellqJe3wemFLO5O" /><figcaption>Photo by <a href="https://unsplash.com/@altumcode?utm_source=medium&amp;utm_medium=referral">AltumCode</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>⚠️ <strong>!important:</strong> Before diving into this article, I recommend checking out this post on <a href="https://phpstan.org/blog/generics-by-examples">Generics by Example</a> for additional context and a helpful example.</p><p>Every time we create a new entity, we have to set up a corresponding repository and implement the usual methods like findOne() and findAll(). It gets really frustrating copying and pasting the same code from one repository to another. Plus, in some projects, you&#39;ll even find inconsistencies in method names—like findOne() in one place and just find() in another. It’s a small thing, but it adds up and can get pretty annoying</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*dIHX8t9JTXrhzhMAqqLnMA.gif" /></figure><p>What if I told you that with PHP generics, we can implement all the most useful repository methods just once? No more repeating yourself for every entity. Let’s dive in and see how to make it happen:</p><h4>Step 1: Create an interface that will represent your usual repository methods</h4><pre>/**<br> * @template T<br> */<br>interface RepositoryInterface<br>{<br>    /**<br>     * @param T $entity<br>     */<br>    public function save(mixed $entity): void;<br><br>    /**<br>     * @param array&lt;mixed&gt; $criteria<br>     * @param null|array&lt;mixed&gt; $orderBy<br>     *<br>     * @return ?T<br>     */<br>    public function findOneByOrNull(array $criteria, array $orderBy = null);<br><br>    /**<br>     * @param array&lt;mixed&gt; $criteria<br>     * @param null|array&lt;mixed&gt; $orderBy<br>     *<br>     * @return T<br>     */<br>    public function findOneBy(array $criteria, array $orderBy = null);<br><br>    /**<br>     * @return ?T<br>     */<br>    public function findOneByIdOrNull(int $id);<br><br>    /**<br>     * @return T<br>     */<br>    public function findOneById(int $id);<br><br>    /**<br>     * @return array&lt;T&gt;<br>     */<br>    public function findAll(): array;<br><br>    /**<br>     * @param array&lt;mixed&gt; $criteria<br>     * @param null|array&lt;mixed&gt; $orderBy<br>     *<br>     * @return array&lt;T&gt;<br>     */<br>    public function findBy(array $criteria, ?array $orderBy = null, ?int $limit = null, ?int $offset = null): array;<br><br>    /**<br>     * @param T $entity<br>     */<br>    public function remove(mixed $entity): void;<br><br>    public function store(): void;<br>}</pre><p><strong>T </strong>will represent the type object that will use next.</p><h4>Step 2: Let create our unique implemention for this methods</h4><pre>**<br> * @template T<br> *<br> * @implements RepositoryInterface&lt;T&gt;<br> */<br>abstract class DoctrineRepository implements RepositoryInterface<br>{<br>    /**<br>     * @param EntityManagerInterface $entityManager<br>     * @param $repository<br>     */<br>    public function __construct(<br>        private readonly EntityManagerInterface $entityManager,<br>        private $repository<br>    ) {<br>    }<br><br>    /**<br>     * @param T $entity<br>     *<br>     * @return void<br>     */<br>    public function save(mixed $entity): void<br>    {<br>        $this-&gt;entityManager-&gt;persist($entity);<br>    }<br><br>    /**<br>     * @return T|null<br>     */<br>    public function findOneByOrNull(array $criteria, array $orderBy = null)<br>    {<br>        return $this-&gt;repository-&gt;findOneBy($criteria, $orderBy);<br>    }<br><br>    /**<br>     * @return T|null<br>     */<br>    public function findOneByIdOrNull(int $id)<br>    {<br>        return $this-&gt;findOneByOrNull([&#39;id&#39; =&gt; $id]);<br>    }<br><br>    /**<br>     * @return T<br>     */<br>    public function findOneById(int $id)<br>    {<br>        return $this-&gt;findOneBy([&#39;id&#39; =&gt; $id]);<br>    }<br><br>    /**<br>     * @throws EntityNotFound<br>     *<br>     * @return T<br>     */<br>    public function findOneBy(array $criteria, array $orderBy = null)<br>    {<br>        $entity = $this-&gt;repository-&gt;findOneBy($criteria, $orderBy);<br>        if ($entity === null) {<br>            throw new EntityNotFound();<br>        }<br><br>        return $entity;<br>    }<br><br>    /**<br>     * @return array&lt;T&gt;<br>     */<br>    public function findAll(): array<br>    {<br>        return $this-&gt;repository-&gt;findAll();<br>    }<br><br>    /**<br>     * @return array&lt;T&gt;<br>     */<br>    public function findBy(array $criteria, ?array $orderBy = null, ?int $limit = null, ?int $offset = null): array<br>    {<br>        return $this-&gt;repository-&gt;findBy($criteria, $orderBy, $limit, $offset);<br>    }<br><br>    /**<br>     * @param T $entity<br>     */<br>    public function remove(mixed $entity): void<br>    {<br>        $this-&gt;entityManager-&gt;remove($entity);<br>    }<br><br>    public function store(): void<br>    {<br>        $this-&gt;entityManager-&gt;flush();<br>    }<br>}</pre><p>As you can see, the __construct() method is just injecting your actual EntityRepository through composition.</p><p>Now, you might be wondering, &quot;Will my IDE be able to figure out what my methods are returning? 🤔&quot; No need to worry—things will become clear in the next step. Let’s go ahead and create our first entity along with its repository!</p><h4>Step 3: create your entity and doctrine repository</h4><p>let’s create an entity “Message” :</p><pre>use App\Repository\MessageRepository;<br>use Doctrine\ORM\Mapping as ORM;<br><br>#[ORM\Entity(repositoryClass: MessageRepository::class)]<br>class Message<br>{<br>    #[ORM\Id]<br>    #[ORM\GeneratedValue]<br>    #[ORM\Column(type: &#39;integer&#39;)]<br>    private int $id;<br><br>    #[ORM\Column(type: &#39;string&#39;)]<br>    private string $message;<br>}<br><br>.........<br><br>use App\Entity\Message;<br>use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;<br>use Doctrine\Persistence\ManagerRegistry;<br><br><br>class MessageRepository extends ServiceEntityRepository<br>{<br>    public function __construct(ManagerRegistry $registry)<br>    {<br>        parent::__construct($registry, Message::class);<br>    }<br>}</pre><p>⚠️ 👀 <strong>!important:</strong> The MessageRepository is an auto-generated repository when an entity is created. It already includes methods like findOne and find(id). However, in most projects, we prefer using a repository interface rather than interacting directly with the repository itself. This approach makes it easier to create Fake or Stub repositories for unit testing.</p><h4>Step 4: implement our usual method</h4><p>Here’s how to create your MessageRepositoryInterface and implement implementation</p><pre>/**<br> * @implements RepositoryInterface&lt;Message&gt;<br> */<br>interface MessageRepositoryInterface extends RepositoryInterface<br>{<br>}</pre><p>Next, provide a simple implementation:</p><pre>/**<br> * @extends DoctrineRepository&lt;Message&gt;<br> */<br>class MessageDoctrineRepository extends DoctrineRepository implements MessageRepositoryInterface<br>{<br>    public function __construct(<br>        private readonly EntityManagerInterface $entityManager,<br>        private readonly MessageRepository $messageRepository<br>    ) {<br>        parent::__construct($this-&gt;entityManager, $this-&gt;messageRepository);<br>    }<br>}</pre><p>As you can see, we replace the generic type T with the specific Message only without adding code related to the implementation.</p><p>Now, PHPStorm correctly understands the return type of my methods when I inject the MessageRepositoryInterface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tSuF4DNc6bvOvoFQ55w2kg.png" /></figure><h4>Conclusion</h4><p>One big advantage is that generics make your code more reusable, allowing you to create flexible solutions without rewriting the logic for different types. Unfortunately, PHP’s native support for generics is still somewhat limited or will never be supported, and you often have to rely on annotations to get the most out of them.</p><p>So be careful,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*bH8CV6Cc8kgYZy7mGJ9JBA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d217dd44f488" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Symfony: Stop checking for dependency updates]]></title>
            <link>https://medium.com/@ZeroCool001/symfony-stop-checking-for-dependency-updates-7087ea2dd35c?source=rss-6e921b69bd28------2</link>
            <guid isPermaLink="false">https://medium.com/p/7087ea2dd35c</guid>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[dependabot]]></category>
            <category><![CDATA[composerphp]]></category>
            <category><![CDATA[composer]]></category>
            <dc:creator><![CDATA[Ismaile ABDALLAH]]></dc:creator>
            <pubDate>Wed, 19 Jun 2024 20:55:40 GMT</pubDate>
            <atom:updated>2024-06-19T20:55:40.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iyS4BFMJMpvceWCT8SvxEA.png" /></figure><p>We all love to dive into feature coding while completely ignoring the <strong>composer.json</strong> file, until, of course, we need a new feature that’s only available in the next version of a dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Vgmx66Pom8jLkG4WyvbdWw.gif" /></figure><p>That’s when we realize we’re three versions behind. Panic! Updating now means a delightful day of fighting deprecations for every version we’ve missed.</p><p>Meet <a href="https://docs.github.com/fr/code-security/dependabot/dependabot-alerts/about-dependabot-alerts"><strong>Dependabot</strong></a>: your friendly, automated dependency manager on GitHub. <strong>Dependabot</strong> scans your projects for outdated dependencies and creates pull requests to update them. It guarantees security and easy updating of your project. With Dependabot, you’ll never be behind on updates again, making maintenance easier and leaving you more time to concentrate on coding the fun stuff!</p><h4>Let’s configure it</h4><p>We will take a Symfony project as example but you can configure it with any project you have</p><p>Create <strong>dependabot.yml</strong> file and store it in <strong>.gihub </strong>directory</p><pre>version: 2<br>updates:<br>  - package-ecosystem: &quot;composer&quot; # Using Composer for PHP dependencies<br>    directory: &quot;/&quot; # The directory where your composer.json file is located<br>    schedule:<br>      interval: &quot;daily&quot; # Check for updates daily<br>    commit-message:<br>      prefix: &quot;chore&quot; # Prefix for commit messages<br>    open-pull-requests-limit: 10 # Limit pull requests opened by Dependabot<br>    groups:<br>      symfony:<br>        patterns:<br>          - &quot;symfony/*&quot; # Update all Symfony dependencies together</pre><p>With this configuration, GitHub will automatically check for dependency updates and create pull requests for you.</p><p>As shown under groups.symfony.patterns, this setup will simplify our workflow when Symfony releases multiple package updates simultaneously.</p><p>here a example of symfony update pull request</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ba3K721YobhOMuFDFrgIA.png" /></figure><p>Instead of generating 11 separate PRs for each Symfony component, Dependabot will consolidate them into a single PR.</p><h4>ℹ️ You can run the update check manually</h4><p>Follow 👇👇👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjvOQP9m9ziAmdKqZk-dHA.png" /></figure><p>Don’t let obsolete dependencies slow you down. Adopt <strong>Dependabot</strong> and keep your projects secure and up-to-date 💪💪.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*j4j8EuU1sfWF9u_S8ju1Cg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7087ea2dd35c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to become better Developer]]></title>
            <link>https://medium.com/@ZeroCool001/how-to-become-better-developer-c8c195de87e8?source=rss-6e921b69bd28------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8c195de87e8</guid>
            <dc:creator><![CDATA[Ismaile ABDALLAH]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 12:45:14 GMT</pubDate>
            <atom:updated>2022-12-06T12:45:14.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XHQtFi8OYXsdLcDV" /><figcaption>Photo by <a href="https://unsplash.com/@jacksloop?utm_source=medium&amp;utm_medium=referral">Jack Sloop</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Don’t be afraid of what you don’t know</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*ZAMqLj_UqxoIFwXg" /><figcaption>Source : giphy.com</figcaption></figure><h4>Avoid these sentences :</h4><ul><li>“I know only JavaScript, i can not fix this python script”</li><li>“I can’t fix this php script because I never learned php during my training ”</li></ul><p>As a developer the programming language is a tool, you should not be afraid to go to the unknown and test new stuff</p><h3>Work Work Work</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*p9wkkkHDMp5iVrR_" /><figcaption>Source : giphy.com</figcaption></figure><ul><li>Test, Break, Repair : don’t be afraid to test new stuff, you can for exemple install Php in your computer with mysql database, and try to create a user registration form.</li><li>Try the same thing with another programming language. Example NodeJs</li><li>If you watch a youtube video of a developer, don’t just watch, practice at the same time</li></ul><h3>Understand things</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*K8p78gOFMCyFN0ov" /><figcaption>Source : giphy.com</figcaption></figure><ul><li>Never copy the code without understanding it. Why, if you have a bug on this code, you will never solve it because you never understood it</li><li>Google is your friend</li><li>Ask for help when you don’t understand</li><li>Use <a href="https://en.wikipedia.org/wiki/Rubber_duck_debugging">rubber duck debugging</a> with your colleague</li><li>There is no stupid question</li></ul><h3>KISS</h3><p>Keep It Simple, Stupide</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/0*FqYSAy87xXWTo-R-" /><figcaption>Source : giphy.com</figcaption></figure><ul><li>When you code, think of the developer who will come after you</li><li>Learn clean code principle by Robert C.Martin</li></ul><h3>FOCUS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*mynjo5TvWBuhSCqU" /><figcaption>Source : giphy.com</figcaption></figure><ul><li>Try to have a period of concentration with the <a href="https://pomofocus.io/">Pomodoro</a> technique for example</li><li>Write pseudo code on paper before starting a complex algorithm</li><li>You can use headphones if you are in an open space</li></ul><h3>Read</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/0*6BtvQU8kcGPUnpAG" /><figcaption>Source : giphy.com</figcaption></figure><p>Try to read :</p><ul><li><a href="https://medium.com/">https://medium.com</a></li><li><a href="https://dev.to/">https://dev.to/</a></li><li><strong>[Book] Clean Code</strong> de Robert C.Martin (Uncle Bob)</li><li><strong>[Book] </strong>Software craft (for french developer)</li></ul><h3>Control your ego</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*LSRUBKtoQ5BFX4Iw" /><figcaption>Source : giphy.com</figcaption></figure><ul><li>Always stay humble, don’t get a big head</li><li>Learn from anyone. From a junior to a senior</li><li>Strive to be the best without crushing others</li><li>Understand and accept that you will make mistakes</li><li>You are not “your” code</li><li>There’s always someone better than us</li></ul><h3>Conclusion</h3><p>may the force be with you</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*DcDisYLRiaiiiCme" /><figcaption>Source : giphy.com</figcaption></figure><p>Here I am sharing with you the tips that helped me to raise my level of development and always helps me to learn new things. <br>I hope this will help you 😇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8c195de87e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ How to Encrypt And Decrypt a varchar with doctrine and Symfony]]></title>
            <link>https://medium.com/@ZeroCool001/how-to-encrypt-and-decrypt-a-varchar-with-doctrine-and-symfony-4559a77a1699?source=rss-6e921b69bd28------2</link>
            <guid isPermaLink="false">https://medium.com/p/4559a77a1699</guid>
            <category><![CDATA[doctrine]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[encryption]]></category>
            <dc:creator><![CDATA[Ismaile ABDALLAH]]></dc:creator>
            <pubDate>Sun, 20 Nov 2022 09:43:57 GMT</pubDate>
            <atom:updated>2022-11-20T09:48:23.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lbvig32ap9HLuSQI" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Sometime we want to encrypt some data directly in database, using Symfony and doctrine. But we want to do it automatically, i mean we don’t want to encrypt manually the data before save it, and decrypt it, when we get the data.</p><p>By creating a new doctrine type we can encrypt and decrypt magically the data. Let see together the steps.</p><h3>Step 1 : Create a service responsible for encryption and decryption</h3><pre>interface EncryptionEngineInterface<br>{<br>    public function encrypt(string $data): string;<br><br>    public function decrypt(string $data): string;<br>}</pre><p>First of all, using an interface will make our life easier the day we want to change our encryption method.</p><p>Let use OpenSsl Encryption implementaion</p><pre>final class EncryptionOpenSslEngine implements EncryptionEngineInterface<br>{<br>    public function __construct(<br>        private readonly string $sslCiphering = &#39;AES-128-CTR&#39;,<br>        private readonly int $sslOption = 0,<br>        private readonly string $sslEncryptionIv = &#39;1234567891011121&#39;,<br>        private readonly string $sslEncryptionKey = &#39;EncryptionKey&#39;,<br>    ) {<br>    }<br><br>    public function encrypt(string $data): string<br>    {<br>        return openssl_encrypt(<br>            $data,<br>            $this-&gt;sslCiphering,<br>            $this-&gt;sslEncryptionKey,<br>            $this-&gt;sslOption,<br>            $this-&gt;sslEncryptionIv<br>        );<br>    }<br><br>    public function decrypt(string $data): string<br>    {<br>        return openssl_decrypt(<br>            $data,<br>            $this-&gt;sslCiphering,<br>            $this-&gt;sslEncryptionKey,<br>            $this-&gt;sslOption,<br>            $this-&gt;sslEncryptionIv<br>        );<br>    }<br>}</pre><p>⚠️ Dont forget to have openssl php extension installed ⚠️</p><h3>Step 2 : Create a new doctrine type</h3><pre>use Doctrine\DBAL\Types\StringType;<br><br>final class EncryptType extends StringType<br>{<br>    public const NAME = &#39;encrypt&#39;;<br><br>    private EncryptionEngineInterface $encryptionEngine;<br><br>    public function setEncryptionEngine(EncryptionEngineInterface $encryptionEngine): void<br>    {<br>        $this-&gt;encryptionEngine = $encryptionEngine;<br>    }<br><br>    public function convertToDatabaseValue($value, AbstractPlatform $platform): string<br>    {<br>        return $this-&gt;encryptionEngine-&gt;encrypt($value);<br>    }<br><br>    public function convertToPHPValue($value, AbstractPlatform $platform): string<br>    {<br>        return $this-&gt;encryptionEngine-&gt;decrypt($value);<br>    }<br><br>    public function canRequireSQLConversion(): bool<br>    {<br>        return true;<br>    }<br><br>    public function getName(): string<br>    {<br>        return self::NAME;<br>    }<br>}</pre><p>Just override the both method <strong><em>convertToDatabaseValue</em></strong> and <strong><em>convertToPHPValue</em></strong> to encrypt and decrypt data by using EncryptionEngineInterface already created.</p><h3>Step 3 : Declare your service and doctrine type</h3><p>In your services.yaml</p><pre>services:<br>    App\EncryptionEngineInterface:<br>        class: App\EncryptionOpenSslEngine<br>        public: true</pre><p>And in your kernel.php file, override boot method to declare your new doctrine type and inject your encryptionServiceInterface</p><pre>public function boot()<br>    {<br>        parent::boot();<br>        $this-&gt;addEncryptTypeToDoctrine();<br>    }<br><br>    private function addEncryptTypeToDoctrine(): void<br>    {<br>        if (Type::hasType(EncryptType::NAME) === false) {<br>            /** @var EncryptionEngineInterface $encryptionEngine */<br>            $encryptionEngine = self::getContainer()-&gt;get(EncryptionEngineInterface::class);<br>            Type::addType(EncryptType::NAME, EncryptType::class);<br>            /** @var EncryptType $encrypt */<br>            $encrypt = Type::getType(EncryptType::NAME);<br>            $encrypt-&gt;setEncryptionEngine($encryptionEngine);<br>        }<br>    }</pre><h3>Step 4 : Use your new doctrine type</h3><pre>#[ORM\Entity()]<br>class Entity<br>{<br>    #[ORM\Id]<br>    #[ORM\GeneratedValue]<br>    #[ORM\Column(type: &#39;integer&#39;)]<br>    private int $id;<br>    <br>    #[ORM\Column(type: EncryptType::NAME)]<br>    private string $secret;<br>}</pre><p>Then use directly your type in you doctrine column definition, and the secret attribute will be encrypted before insert and decrypted when we get the entity.</p><p>Enjoy 😃, tell me your opinion in comment</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4559a77a1699" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>