<?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 Samir Rustamov on Medium]]></title>
        <description><![CDATA[Stories by Samir Rustamov on Medium]]></description>
        <link>https://medium.com/@samir_rustamov?source=rss-33092e3d15b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b5lx-o1Sud1hOJ6Urs0BMA@2x.jpeg</url>
            <title>Stories by Samir Rustamov on Medium</title>
            <link>https://medium.com/@samir_rustamov?source=rss-33092e3d15b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:58:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samir_rustamov/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[Negative Space Programming: What You Don’t Write Matters Even More Than What You Do]]></title>
            <link>https://medium.com/@samir_rustamov/negative-space-programming-what-you-dont-write-matters-even-more-than-what-you-do-fe28dd05648a?source=rss-33092e3d15b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe28dd05648a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[deep-thoughts]]></category>
            <category><![CDATA[out-of-the-box]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Samir Rustamov]]></dc:creator>
            <pubDate>Sat, 25 Oct 2025 00:18:08 GMT</pubDate>
            <atom:updated>2025-10-25T13:00:38.953Z</atom:updated>
            <content:encoded><![CDATA[<p>We also talk about positive space programming, but the program has a specific element of “negative space programming,” the concept that what you don’t write matters more than what you do.</p><blockquote>Imagine you’re in a modern art museum, looking at a painting made of mostly white canvas with a few strategic black lines. Your graphic designer friend calmly says to you, “See how the empty space defines the subject? It’s <a href="https://en.wikipedia.org/wiki/Negative_space">negative space</a>. It’s not nothingness, it’s a deliberate absence.&quot;</blockquote><p>What can we do to improve our codebase? What new functions, algorithms, abstractions should be added to it? But maybe the true magic resides in what we don’t write — or don’t put down there.</p><blockquote><strong>The philosophy: The more you don’t have, the more you get.<br> </strong><br>In human relationships, we realize that boundaries are not about constructing walls to separate; they are about establishing the possibility of connection to be healthy. Not every text you receive needs to be responded to now. Not that you have to explain yourself at length. Sometimes the pause communicates more than words can. Code works the same way. But every line you write is a promise. It’s technical debt in waiting. It is one more thing you can break one more thing that future developers need to know, one more surface area for bugs to hide. The best solutions are often simple — nothing to do with adding code, and removing.</blockquote><blockquote><a href="https://www.goodreads.com/quotes/19905-perfection-is-achieved-not-when-there-is-nothing-more-to"><em>Perfection is realized not when there is nothing additional added, but when there is nothing left to take away.</em></a></blockquote><p>And this is not mere poetic wisdom. This is practical to developing software that sticks. What Negative Space Programming Really Means. Negative space programming is about consciously choosing to limit, reduce, or exclude; It’s the practice of:</p><ul><li><strong>Using language features that prevent errors rather than catching them</strong></li><li><strong>Designing APIs that make mistakes impossible</strong></li><li><strong>Choosing not to handle edge cases that shouldn’t exist</strong></li><li><strong>Letting the type system do the work instead of writing defensive code</strong></li></ul><p>It’s the difference between constructing a fence around a cliff and not constructing the path to the cliff in the first place.</p><p><strong>Example 1</strong>: Optional Chaining vs. Defensive Null Checks<br>Here is how most people used to write JavaScript:</p><pre>function getUserCity(user) { <br>  if (user &amp;&amp; user.address &amp;&amp; user.address.city) {<br>     return user.address.city;<br>  } <br>  return ‘Unknown’;<br>}</pre><p>That’s six lines of defensive programming. At every level we protect against null or undefined. It works, but take a peek at what we say, what we are really saying: “This data structure is something I do not trust, so I am going to check at every stage.” We make an effort to prove all the steps correctly. Now with optional chaining:</p><pre>function getUserCity(user) { <br>  return user?.address?.city ?? ‘Unknown’;<br>}</pre><p>One line. Same functionality.</p><p>“Most importantly, we’ve eliminated the five lines of noise. Negative space makes it apparent that whatever you do on a path to a city, if anything in the way is missing, default. This is not mere syntactic sugar. It’s a shift in mindset. But we’re not writing error handling code — we’re using a language feature that reflects safe navigation. The lack of those nested if-statements is by design. That’s negative space.</p><p><strong>Example 2</strong>: Type Systems as Boundaries.</p><p>Think about defining personal relationships. For the example of your coworker’s suggestion, when it comes to work “I don’t talk about work after 7 PM” — you don’t take it too tough. You’re building a container where healthy interaction can occur. You’re delineating what will happen, and everyone knows in advance of when that will happen. TypeScript has the same nature:</p><pre>function processPayment(amount, currency) {<br>    // Hope and pray amount is a number. <br>    // Hope and pray currency holds true. <br>    // Write validation logic. <br>    if (typeof amount !== &#39;number&#39;) {<br>        throw new Error(&#39;Amount must be a number&#39;);<br>    } <br>     if (! [&#39;USD&#39;, &#39;EUR&#39;, &#39;GBP&#39;].includes(currency)) {<br>         throw new Error(&#39;Invalid currency&#39;);<br>     } <br>    // Finally do some actual work…<br>}</pre><p>That’s exhausting. We are writing all this code just to test our most basic assumptions. Now watch us at the type application, to see what happens:</p><pre>// Without constraints<br> <br>type Currency = ‘USD’ | ‘EUR’ | ‘GBP’;<br><br>function processPayment(amount: number, currency: Currency) { <br> // The actual work starts here. <br> // TypeScript already made sure our input is valid. <br>}</pre><p>See what we didn’t write? All that validation code. It doesn’t actually exist in our implementation because we forced it to the boundary: the type system. Before we even deploy function with that type, the compiler helps to prevent invalid calls. The negative space here is runtime validation not there at all. Because we chose to omit writing, our code has proven simpler, quicker, and easier to maintain.</p><p><strong>Example 3</strong>: Making Impossible States Impossible. Here’s a pattern that comes up again and again:</p><pre>const UserProfile = ({ user }) =&gt; {<br>  if (user.isLoading &amp;&amp; user.error) {<br>    // Wait, can we be loading AND have an error?<br>    // This shouldn&#39;t happen, but...<br>  }<br>  <br>  if (user.isLoading) {<br>    return &lt;Spinner /&gt;;<br>  }<br>  <br>  if (user.error) {<br>    return &lt;Error message={user.error} /&gt;;<br>  }<br>  <br>  if (user.data) {<br>    return &lt;Profile data={user.data} /&gt;;<br>  }<br>  <br>  return null; // What even is this state?<br>}</pre><p>This code is a bit of defensive programming taken to the edge. We’re dealing with every flag combination possible, including the nonsensical. Kind of like you’re planning for an argument that never happened, and you’ve got to get prepared for every sort of hypothetical answer. Here is how we could do that with negative space:</p><pre>type UserState = <br>  | { status: &#39;loading&#39; }<br>  | { status: &#39;error&#39;; error: string }<br>  | { status: &#39;success&#39;; data: UserData };<br><br>const UserProfile = ({ user }: { user: UserState }) =&gt; {<br>  switch (user.status) {<br>    case &#39;loading&#39;:<br>      return &lt;Spinner /&gt;;<br>    case &#39;error&#39;:<br>      return &lt;Error message={user.error} /&gt;;<br>    case &#39;success&#39;:<br>      return &lt;Profile data={user.data} /&gt;;<br>  }<br>}</pre><p>Notice what’s missing? All those impossible checks on state. We’re dealing with an error of <strong><em>loading and error</em> </strong>and we don’t handle it because we’ve designed our data structure so that state can’t exist. The negative space is we didn’t write the code because we made it impossible to need it.</p><p>That is similar to clear and honest communication in a relationship. When everybody knows the whole you don’t have to wrangle mixed signals. The clarity alone avoids the miscommunication.</p><p><strong>When Not to Use Negative Space</strong></p><p>The point is that negative space programming isn’t about being clever or minimalist just for smarts sake. Sometimes you require explicit code. It is sometimes clearer if the verbose version is written. If you’re dealing with external data that you don’t control, defensive checks may be in order. Explicit validation in building a library that is required to provide valuable error messages is a good idea indeed. if its your team is not well versed in TypeScript, adding types may confuse more than illuminate. The key is intentionality. You’re getting through, are you throwing away code because it should be in some form that is real and valid, or are you lazy? Are you using logical constraints, or are you twisting your layout around to spare a few lines of code? Negative space is about thoughtful absence, not careless deletion.</p><p><strong>The Deeper Lesson</strong></p><p>It is a move away from the ‘how do I fix this problem? to “how to do it right” to “how can I stave off this problem from happening?” With writing code this time now I stop and wait to add lines. I ask: “ Does this have to exist anyway? Anything that I can design and that I don’t need this check on? Can the type system, the API design, or the architecture make this code redundant?” More frequently than you should expect, the answer is yes.</p><p><strong>The Space Between</strong></p><p>In design, the white space in between elements allows them to breathe. The pauses between words in conversation allow meaning to take its time to land during conversation. In code, the lines we don’t write are what gives our software clarity.</p><p>Also check: <a href="https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/">https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe28dd05648a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple Guide to Better Routing and Middleware with TypeScript Decorators]]></title>
            <link>https://medium.com/@samir_rustamov/streamline-your-express-app-a-simple-guide-to-better-routing-and-middleware-with-typescript-24454c535720?source=rss-33092e3d15b------2</link>
            <guid isPermaLink="false">https://medium.com/p/24454c535720</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Samir Rustamov]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 23:51:29 GMT</pubDate>
            <atom:updated>2024-03-10T00:26:38.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6AdHvHX0_4cAu4uXWFA6w.png" /></figure><blockquote>Sometimes, when creating large Express applications, routing structures and middleware can become complicated, unless you are using a framework. As an escape from this, we can turn to a powerful tool in the Typescript arsenal: <strong>Decorators</strong>.</blockquote><p><a href="https://www.typescriptlang.org/docs/handbook/decorators.html">Enter TypeScript decorators</a>; It may seem mysterious at first, but it’s essentially a game-changer for developers looking to take their Nodejs apps to new heights.Through practical examples and step-by-step instructions, we will discover how decorators can not only simplify your code, but also make it more expressive and flexible.</p><h4>Step 1: Initialize Project</h4><p>Open your terminal or command prompt, and follow these steps to create a new directory for your project and initialize it with a package.json file:</p><pre>mkdir express-decorators-guide<br><br>cd express-decorators-guide<br><br>npm init -y</pre><h4>Step 2: Install TypeScript and Essential dependencies</h4><pre>npm install express reflect-metadata<br><br>npm install typescript @types/express @types/node ts-node nodemon --save-dev</pre><h4>Step 3: Create a TypeScript Configuration File</h4><pre>npx tsc --init</pre><p>Enabling Decorators</p><p>Open your tsconfig.json file, which you created during the initial setup. We need to make sure that TypeScript is configured to recognize and compile decorator syntax. Add the following options within the compilerOptions section:</p><ol><li><a href="https://www.typescriptlang.org/tsconfig#emitDecoratorMetadata">emitDecoratorMetadata</a></li><li><a href="https://www.typescriptlang.org/tsconfig#experimentalDecorators">experimentalDecorators</a></li></ol><pre>&quot;experimentalDecorators&quot;: true,<br>&quot;emitDecoratorMetadata&quot;: true</pre><p>Your compilerOptions should look something like this:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    ...<br>    &quot;target&quot;: &quot;es2016&quot;,<br>    &quot;module&quot;: &quot;commonjs&quot;,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true,<br>    &quot;strict&quot;: true,<br>    &quot;skipLibCheck&quot;: true    ,<br>    &quot;experimentalDecorators&quot;: true,<br>    &quot;emitDecoratorMetadata&quot;: true<br>    ...<br>  }<br>}</pre><p>Let’s organize the project structure to include the necessary folders and files for controllers, decorators, and startup logic, along with the main entry file index.ts.</p><pre>express-decorators-guide/<br>├── controllers/<br>│   ├── index.controller.ts<br>│   └── orders.controller.ts<br>├── decorators/<br>│   └── http/<br>│       ├── methods.ts<br>│       └── middleware.ts<br>├── startup/<br>│   └── registerRoutes.ts<br>└── index.ts<br>├── package.json<br>├── tsconfig.json</pre><h3>Decorators for Express Routing</h3><p>The methods.ts file in our decorators/http directory is where we define our HTTP method decorators, such as @Get and @Post. These decorators will enable us to annotate controller methods with routing information, making our controllers cleaner and more expressive.</p><pre>// decorators/http/methods.ts<br><br>function methodDecoratorFactory(method: string) {<br>    return function(path: string): MethodDecorator {<br>        return function(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {<br>            Reflect.defineMetadata(&quot;route&quot;, path, target, propertyKey);<br>            Reflect.defineMetadata(&quot;method&quot;, method, target, propertyKey);<br>        };<br>    };<br>}<br><br>export function Post(path: string): MethodDecorator {<br>    return methodDecoratorFactory(&quot;post&quot;)(path);<br>}<br><br>export function Get(path: string): MethodDecorator {<br>    return methodDecoratorFactory(&quot;get&quot;)(path);<br>}<br><br>// other HTTP methods can be added here</pre><p>The methodDecoratorFactory function is a higher-order function that creates decorators for different HTTP methods. By calling this factory with &#39;get&#39; or &#39;post&#39;, we generate specific decorators for these HTTP verbs. These decorators then use Reflect.defineMetadata to attach metadata about the route path and method to the controller methods they decorate. This metadata will later be used to register routes in our Express application dynamically.</p><h3>Decorator for Express Middleware</h3><p>decorators/http/middleware.ts</p><pre>import { RequestHandler } from &quot;express&quot;;<br><br>export function Middleware(middleware: RequestHandler): MethodDecorator {<br>    return function(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {<br>        const middlewares: RequestHandler[] = Reflect.getMetadata(&quot;middlewares&quot;, target, propertyKey) || [];<br>        middlewares.push(middleware);<br>        Reflect.defineMetadata(&quot;middlewares&quot;, middlewares, target, propertyKey);<br>    };<br>}</pre><h3>Dynamic Route Registration</h3><p>The registerRoutes.ts file contains the logic to dynamically scan controller instances for routing information stored in metadata and register those routes with the Express application. This process involves a few key functions: registerControllers and registerRoutes.</p><pre>import {Application as App, RequestHandler} from &quot;express&quot;;<br>import fs from &quot;fs&quot;;<br><br>type HttpMethod = &#39;get&#39; | &#39;post&#39; | &#39;put&#39; | &#39;delete&#39; | &#39;patch&#39; | &#39;options&#39; | &#39;head&#39;;<br><br>export function registerControllers(app: App, path: string) {<br>    fs.readdirSync(path).forEach(file =&gt; {<br>        const filePath = `${path}/${file}`;<br>        if (fs.lstatSync(filePath).isDirectory()) {<br>            registerControllers(app, filePath);<br>        } else if (filePath.endsWith(&quot;.controller.ts&quot;)) {<br>            const controller = require(filePath);<br>            const controllerInstance = new controller[Object.keys(controller)[0]]();<br>            registerRoutes(app, controllerInstance);<br>        }<br>    });<br>}<br><br>// for one controller register.<br>// if you want set controller manual <br>// then you can use it<br>export function registerController(app: App, controller: any) {<br>    registerRoutes(app, new controller());<br>}<br><br>export function registerRoutes(app: App, controllerInstance: any) {<br>    Object.getOwnPropertyNames(Object.getPrototypeOf(controllerInstance)).forEach(methodName =&gt; {<br>        // Retrieve route handler, path, HTTP method, and middlewares from metadata<br>        const routeHandler = controllerInstance[methodName];<br>        const path: string = Reflect.getMetadata(&quot;route&quot;, controllerInstance, methodName);<br>        const method: HttpMethod = Reflect.getMetadata(&quot;method&quot;, controllerInstance, methodName) as HttpMethod;<br>        <br>        // get middlewares from Middeware decorators<br>        const middlewares: RequestHandler[] = Reflect.getMetadata(&quot;middlewares&quot;, controllerInstance, methodName) || [];<br>        // If the method is valid, register the route with middlewares and the handler<br>        if (path &amp;&amp; method) {<br>            const isMethodValid = method in app &amp;&amp; typeof app[method] === &#39;function&#39;;<br>            if (isMethodValid) {<br>                (app[method] as Function)(path, ...middlewares, routeHandler);<br>            } else {<br>                console.warn(`Unsupported method &#39;${method}&#39; for route ${path}`);<br>            }<br>        }<br>    });<br>}</pre><ul><li>registerControllers Function: This function scans a given directory for any files ending with .controller.ts, requiring them and then registering their routes using the registerRoutes function. This recursive approach ensures that all controllers, even in nested directories, are discovered and their routes registered.</li><li>registerRoutes Function: The core function that iterates over each method of a controller instance, retrieves the metadata defined by our decorators (@Get, @Post, etc.), and registers the appropriate routes with Express. It also supports middleware, which can be applied to routes as needed.</li></ul><h3>Finally, our index.ts file looks like this</h3><pre>import &quot;reflect-metadata&quot;;<br>import express from &quot;express&quot;;<br>import { registerControllers } from &quot;./startup/registerRoutes&quot;;<br><br>const app = express();<br><br>// Dynamically register all controllers in the &#39;controllers&#39; directory<br>registerControllers(app, __dirname + &quot;/controllers&quot;);<br><br>app.listen(3000, () =&gt; {<br>    console.log(&quot;Server is running on port 3000&quot;);<br>});</pre><p>This approach to registering routes defined through decorators in any controller within the controllers directory.</p><h3>Defining Controllers with Decorators</h3><h4>The IndexController</h4><p>The index.controller.ts showcases a simple route that returns a welcoming message:</p><pre>// controllers/index.controller.ts<br><br>import { Get } from &quot;../decorators/http/methods&quot;;<br>import { Request, Response, NextFunction } from &quot;express&quot;;<br><br>export class IndexController {<br><br>    @Get(&#39;/&#39;)<br>    public welcome(request: Request, response: Response, next: NextFunction) {<br>        return response.json({ <br>            message: &#39;Hello from the index controller!&#39; <br>        });<br>    }<br>}</pre><h4>The Orders Controller with Route and Middleware</h4><p>The orders.controller.ts includes a middleware decorator to demonstrate how we can apply middleware logic selectively to our routes, such as for authentication:</p><pre>// src/controllers/orders.controller.ts<br><br>import { Get, Post } from &quot;../decorators/http/methods&quot;;<br>import { Middleware } from &quot;../decorators/http/middleware&quot;;<br>import { Request, Response, NextFunction } from &quot;express&quot;;<br><br>export class OrdersController {<br><br>    @Get(&#39;/orders&#39;)<br>    public index(request: Request, response: Response, next: NextFunction) {<br>        return response.status(200).json({ message: &#39;Orders list&#39; });<br>    }<br><br>    @Post(&#39;/orders&#39;)<br>    @Middleware((req: Request, res: Response, next: NextFunction) =&gt; {<br>        // Example middleware: check if the user is authenticated<br>        next();<br>    })<br>    //@Middleware(...) another middleware<br>    public create(request: Request, response: Response, next: NextFunction) {<br>        return response.status(201).json({ message: &#39;Order created&#39; });<br>    }<br>}</pre><h3>There’s only one step left. start your project and see the result :)</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24454c535720" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Property Dependency Injection in Laravel]]></title>
            <link>https://medium.com/@samir_rustamov/automating-property-dependency-injection-in-laravel-a7e99a0ca834?source=rss-33092e3d15b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7e99a0ca834</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Samir Rustamov]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 10:43:12 GMT</pubDate>
            <atom:updated>2024-02-05T22:01:50.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Dependency Injection" src="https://cdn-images-1.medium.com/max/1022/1*qRtohYk3CJ3jgdV6JYkSHQ.png" /></figure><p>Hello Laravel enthusiasts! Have you ever tried automating traditional dependency injection methods in Laravel? Today I will show you a different approach that combines Laravel’s framework with PHP features.</p><blockquote>Dependency Injection (DI) is the cornerstone of the Laravel architecture, facilitating better testing and modular design. However, standard DI methods lack the automatic injections available in other web frameworks.<br>e.g : <a href="https://docs.spring.io/spring-framework/reference/core/beans/annotation-config/autowired.html">https://docs.spring.io/spring-framework/reference/core/beans/annotation-config/autowired.html</a></blockquote><p><em>The feature we’re going to make looks almost like this:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8cvaYdpKt2lGlVUNjO4lA.png" /></figure><h3>Crafting a Custom Application Class</h3><p>We start the adventure by enhancing Laravel’s <strong>Application</strong> class. We create a customized Dependency Injection (DI) mechanism that scans specific namespaces.</p><pre>&lt;?php<br><br>namespace App\Foundation;<br><br>use App\Attributes\Inject;<br>use Exception;<br>use ReflectionClass;<br><br>class Application extends \Illuminate\Foundation\Application<br>{<br>    protected static array $injectablePropertiesCache = [];<br>    <br>    protected array $shouldScanNamespacePrefixes = [<br>        &#39;App\Http\Controllers\\&#39;,<br>        &#39;App\Services\\&#39;,<br>    ];<br><br>    public function build($concrete)<br>    {<br>        $object = parent::build($concrete);<br><br>        return $this-&gt;resolveInjectedProperties($object);<br>    }<br><br>    protected function resolveInjectedProperties($object)<br>    {<br>        if ($this-&gt;shouldScanInjectableProperties($object)) {<br><br>            if ($this-&gt;resolveInjectablePropertiesFromCacheIfPossible($object)) {<br>                return $object;<br>            }<br><br>            $reflectionClass = new ReflectionClass($object);<br><br>            $reflectionProperties = $reflectionClass-&gt;getProperties();<br><br>            // Cache the injectable properties for we will know if we have already resolved them<br>            $this-&gt;cacheResolvedInjectableProperties($object);<br><br>            foreach ($reflectionProperties as $reflectionProperty) {<br><br>                if ($reflectionProperty-&gt;isInitialized($object)) {<br>                    continue;<br>                }<br><br>                $injectAttribute = $reflectionProperty-&gt;getAttributes(Inject::class)[0] ?? null;<br><br>                if ($injectAttribute) {<br><br>                    if (!$reflectionProperty-&gt;getType()) {<br>                        throw new Exception(&quot;Injectable property {$reflectionProperty-&gt;getName()} must be typed&quot;);<br>                    }<br><br>                    if ($reflectionProperty-&gt;getType()-&gt;isBuiltin()) {<br>                        throw new Exception(&quot;Injectable property {$reflectionProperty-&gt;getName()} must be a class&quot;);<br>                    }<br><br>                    $constructorParameters = $injectAttribute-&gt;newInstance()-&gt;getArgs();<br><br>                    $reflectionProperty-&gt;setValue($object, $this-&gt;make(<br>                        abstract: $reflectionProperty-&gt;getType()-&gt;getName(),<br>                        parameters: $constructorParameters<br>                    ));<br><br>                    $this-&gt;cacheResolvedInjectableProperties($object, $reflectionProperty, $constructorParameters);<br>                }<br>            }<br><br>        }<br><br>        return $object;<br>    }<br><br>    protected function shouldScanInjectableProperties($object): bool<br>    {<br>        $fullNameString = is_object($object) ? get_class($object) : $object;<br><br>        if (!class_exists($fullNameString)) {<br>            return false;<br>        }<br><br>        foreach ($this-&gt;shouldScanNamespacePrefixes as $namespacePrefix) {<br>            if (str_starts_with($fullNameString, $namespacePrefix)) {<br>                return true;<br>            }<br>        }<br><br>        return false;<br>    }<br><br>    /**<br>     * if you use Octane or any other long-running process, this method helps to performance<br>     * because it will not resolve the injectable properties again and again.Otherwise,<br>     * you should cache the resolved injectable properties in a file or redis.<br>     */<br>    public function resolveInjectablePropertiesFromCacheIfPossible(object $object): object|bool<br>    {<br>        if (isset(static::$injectablePropertiesCache[$object::class])) {<br><br>            $cachedInjectableProperties = static::$injectablePropertiesCache[$object::class];<br><br>            foreach ($cachedInjectableProperties as $cachedInjectableProperty) {<br>                $reflectionProperty = $cachedInjectableProperty[&#39;reflectionProperty&#39;];<br>                $reflectionProperty-&gt;setValue($object, $this-&gt;make(<br>                    abstract: $reflectionProperty-&gt;getType()-&gt;getName(),<br>                    parameters: $cachedInjectableProperty[&#39;constructorParameters&#39;]<br>                ));<br>            }<br><br>            return $object;<br>        }<br><br>        return false;<br>    }<br><br>    public function cacheResolvedInjectableProperties($object, $reflectionProperty = null, $constructorParameters = []): void<br>    {<br>        if ($reflectionProperty === null) {<br>            static::$injectablePropertiesCache[$object::class] = [];<br>            return;<br>        }<br><br>        static::$injectablePropertiesCache[$object::class][] = [<br>            &#39;reflectionProperty&#39; =&gt; $reflectionProperty,<br>            &#39;constructorParameters&#39; =&gt; $constructorParameters<br>        ];<br>    }<br>}</pre><p>It’s where we set the stage for our custom DI process.</p><h4>Bootstrap Modifications:</h4><p>To include our custom class, a small adjustment in <strong>bootstrap/app.php </strong>is necessary.</p><pre>&lt;?php <br><br>$app = new \App\Foundation\Application(<br>    $_ENV[&#39;APP_BASE_PATH&#39;] ?? dirname(__DIR__)<br>);<br><br>#...other codes</pre><p>This ensures Laravel starts with our enhanced Application class.</p><h4>The Inject Attribute:</h4><p>The Inject attribute is a simple yet good way to declare dependencies right in the property declarations</p><pre>&lt;?php<br><br>namespace App\Attributes;<br><br>use Attribute;<br><br>#[Attribute(Attribute::TARGET_PROPERTY)]<br>class Inject<br>{<br>    public array $args = [];<br><br>    public function __construct(mixed ...$args)<br>    {<br>        $this-&gt;args = $args;<br>    }<br><br>    public function getArgs(): array<br>    {<br>        return $this-&gt;args;<br>    }<br>}</pre><h4>Putting It All Together</h4><p>In FooController, the Inject attribute elegantly injects FooService, showcasing the ease and efficiency of this approach</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Attributes\Inject;<br>use App\Services\FooService;<br>use App\Services\BarService;<br><br>class FooController extends Controller<br>{<br>    #[Inject]<br>    private readonly BarService $fooService;<br><br><br>    // also you can pass parameters to the construct of the FooService<br>    #[Inject(number: 1)]<br>    private readonly FooService $fooService;<br><br><br>    public function index(): array<br>    {<br>        return [<br>            &#39;numberFromFooService&#39; =&gt; $this-&gt;fooService-&gt;getNumber(),<br>            &#39;dataFromBarService&#39; =&gt; $this-&gt;fooService-&gt;getData()<br>        ];<br>    }<br>}</pre><h3>Note :</h3><p>If you are going to use the this feature in large-scale projects, you should find it mandatory to cache the property discovery method so that you do not encounter performance difficulties.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7e99a0ca834" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Untitled Thoughts About Life’s Contrasts]]></title>
            <link>https://medium.com/@samir_rustamov/my-untitled-thoughts-about-lifes-contrasts-e4bf212d01af?source=rss-33092e3d15b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4bf212d01af</guid>
            <category><![CDATA[reality]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[truth-and-life]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[random-thoughts]]></category>
            <dc:creator><![CDATA[Samir Rustamov]]></dc:creator>
            <pubDate>Sat, 30 Dec 2023 22:59:04 GMT</pubDate>
            <atom:updated>2024-04-05T22:08:10.508Z</atom:updated>
            <content:encoded><![CDATA[<p>…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4bf212d01af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an Asynchronous API Handler in Laravel]]></title>
            <link>https://medium.com/@samir_rustamov/creating-an-asynchronous-api-handler-in-laravel-ca5597684d3a?source=rss-33092e3d15b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca5597684d3a</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[advanced]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Samir Rustamov]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 18:22:20 GMT</pubDate>
            <atom:updated>2023-09-27T11:35:51.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itEzJuLa2MqsN0Le2O3Zug.png" /></figure><p>Handling asynchronous API requests is crucial for optimizing the performance and responsiveness of your Laravel application. In this article, we will explore how to create an asynchronous API handler by leveraging PHP 8 attributes, Laravel’s robust ecosystem, and by extending Laravel’s ControllerDispatcher.</p><h3>Introduction</h3><p>In Laravel, asynchronous processing can be essential when dealing with heavy or time-consuming tasks, allowing the application to remain responsive. We will create a system where methods marked with a specific attribute will be processed asynchronously, and the client will receive a response with a unique processId that can be used to poll or notify the client once the processing is completed.</p><h3>Implementation Overview</h3><ol><li>Async Attribute: To mark methods that should be handled asynchronously.</li><li>AbstractApiAsyncWorker: Serves as the base for all asynchronous workers.</li><li>ApiWorkerInterface: Ensures that all worker classes adhere to a consistent structure.</li><li>AsyncApiWorkerJob: Processes the asynchronous tasks.</li><li>AppServiceProvider: Overrides the default ControllerDispatcher with our custom one.</li></ol><h3>Step 1: Creating the Async Attribute</h3><p>The Async attribute is targeted at methods and ensures that the worker class implements the ApiWorkerInterface.</p><pre>&lt;?php<br><br>namespace App\Support\Api\Attributes;<br><br><br>use App\Support\Api\Interfaces\ApiWorkerInterface;<br>use Exception;<br>use Attribute;<br><br>#[Attribute(Attribute::TARGET_METHOD)]<br>class Async<br>{<br>    public function __construct(public string $workerClass)<br>    {<br>        if (!is_subclass_of($this-&gt;workerClass, $interface = ApiWorkerInterface::class)) {<br>            throw new Exception(&quot;The worker must implement the {$interface} interface.&quot;);<br>        }<br>    }<br><br>    public function getWorkerClass(): string<br>    {<br>        return $this-&gt;workerClass;<br>    }<br>}</pre><h3>Step 2: Develop the AbstractApiAsyncWorker</h3><p>The AbstractApiAsyncWorker class is responsible for dispatching the job and processing the request, generating a unique processId for each request.</p><pre>&lt;?php<br><br>namespace App\Support\Api;<br><br>use AllowDynamicProperties;<br>use App\Exceptions\Handler;<br>use App\Jobs\AsyncApiWorkerJob;<br>use Illuminate\Http\Request;<br>use Illuminate\Http\JsonResponse;<br>use Throwable;<br><br>#[AllowDynamicProperties]<br>abstract class AbstractApiAsyncWorker<br>{<br>    protected string $processId;<br><br>    public function __construct(<br>        public $handler,<br>        public array $arguments = [],<br>        public ?Request $request = null,<br>    )<br>    {<br>        $this-&gt;request ??= request();<br><br>        $this-&gt;processId = sha1(implode(&quot;:&quot;,[<br>            $this-&gt;request-&gt;header(&#39;X-Request-Id&#39;,uniqid(microtime(true))),<br>            uniqid(),<br>            $this-&gt;request-&gt;fingerprint()<br>        ]));<br>    }<br><br>    public function getProcessId(): string<br>    {<br>        return $this-&gt;processId;<br>    }<br><br>    public function dispatch(): JsonResponse<br>    {<br>        AsyncApiWorkerJob::dispatchAfterResponse($this)-&gt;onQueue(&#39;api_async_worker&#39;);<br><br>        return response()-&gt;json([<br>            &#39;processId&#39; =&gt; $this-&gt;getProcessId(),<br>            &#39;message&#39; =&gt; &#39;The request is being processed. Please wait for the result.&#39;<br>        ]);<br>    }<br><br><br>    protected function run()<br>    {<br>        try {<br>            $this-&gt;beforeProcess();<br><br>            return $this-&gt;afterProcess(<br>                app()-&gt;call($this-&gt;handler, $this-&gt;arguments)<br>            );<br>        } catch (Throwable $exception) {<br>            return $this-&gt;failed($exception);<br>        }<br>    }<br><br><br>    protected function failed(Throwable $exception) : mixed<br>    {<br>        return app(Handler::class)-&gt;render($this-&gt;request,$exception);<br>    }<br><br>    protected function beforeProcess(): void<br>    {<br>        app()-&gt;instance(&#39;request&#39;, $this-&gt;request);<br>    }<br><br>    protected function afterProcess(mixed $call)<br>    {<br>        return $call;<br>    }<br>}</pre><pre>&lt;?php<br><br>namespace App\Support\Api\Workers;<br><br>use App\Support\Api\AbstractApiAsyncWorker;<br>use App\Support\Api\Interfaces\ApiWorkerInterface;<br><br>class ExampleWorker extends AbstractApiAsyncWorker implements ApiWorkerInterface<br>{<br>    public function process(): mixed<br>    {<br>        $response = $this-&gt;run();<br>    }<br>}</pre><h3>Step 3: Defining the ApiWorkerInterface</h3><p>The ApiWorkerInterface defines the structure that all worker classes must implement, ensuring consistency across different workers.</p><pre>&lt;?php<br><br>namespace App\Support\Api\Interfaces;<br><br>use Illuminate\Http\Request;<br>use Illuminate\Http\JsonResponse;<br><br>interface ApiWorkerInterface<br>{<br>    public function __construct(<br>        $handler,<br>        array $arguments = [],<br>        ?Request $request = null,<br>    );<br><br>    public function getProcessId(): string;<br><br>    public function dispatch(): JsonResponse;<br><br>    public function process(): mixed;<br>}</pre><h3>Step 4: Creating the AsyncApiWorkerJob</h3><p>The AsyncApiWorkerJob is responsible for processing the asynchronous tasks and ensuring that the same job isn&#39;t processed multiple times within a given timeframe.</p><pre>&lt;?php<br><br>namespace App\Jobs;<br><br>use Illuminate\Foundation\Bus\Dispatchable;<br>use App\Support\Api\Interfaces\ApiWorkerInterface;<br>use Illuminate\Bus\Queueable;<br>use Illuminate\Contracts\Broadcasting\ShouldBeUnique;<br>use Illuminate\Contracts\Queue\ShouldQueue;<br>use Illuminate\Queue\InteractsWithQueue;<br>use Illuminate\Queue\SerializesModels;<br><br>class AsyncApiWorkerJob implements ShouldQueue,ShouldBeUnique<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;<br><br><br>    public int $tries = 10;<br><br>    public int $uniqueFor = 180;<br><br>    public int $timeout = 360;<br><br>    public function __construct(<br>        protected ApiWorkerInterface $worker,<br>    ){}<br><br><br>    public function handle(): void<br>    {<br>        $this-&gt;worker-&gt;process();<br>    }<br><br>    public function uniqueId(): string<br>    {<br>        return &#39;worker:&#39;.serialize($this-&gt;worker-&gt;handler);<br>    }<br>}</pre><h3>Step 5: Integrating ControllerDispatcher Override</h3><p>The ControllerDispatcher is a crucial component in Laravel’s routing system, responsible for dispatching a request to a controller method. By overriding this class, we can introduce custom logic to handle methods marked with the Async attribute differently.</p><p>Below is the implementation of the custom ControllerDispatcher:</p><pre>namespace App\Overrides\Routing;<br><br>use App\Support\Api\Interfaces\ApiWorkerInterface;<br>use App\Support\Api\Attributes\Async;<br>use Illuminate\Routing\Route;<br>use Illuminate\Http\Request;<br>use Illuminate\Support\Arr;<br>use ReflectionException;<br>use ReflectionMethod;<br>use Override;<br><br>class ControllerDispatcher extends \Illuminate\Routing\ControllerDispatcher<br>{<br><br>    #[Override]<br>    public function dispatch(Route $route, $controller, $method)<br>    {<br>        // Check if the method has the Async attribute then get its instance<br>        $asyncAttribute = $this-&gt;getControllerMethodAttribute($controller,$method,Async::class);<br>       <br>        if($asyncAttribute) {<br><br>            // Resolve the parameters for the method<br>            $parameters = $this-&gt;resolveParameters($route, $controller, $method);<br><br>            // Extract the Request object from the parameters<br>            $request = Arr::first($parameters, fn ($value) =&gt; $value instanceof Request);<br><br>            // Get the worker class from the Async attribute<br>            $workerClass = $asyncAttribute-&gt;getWorkerClass();<br><br>            // Create an instance of the worker class<br>            /** @var ApiWorkerInterface $apiAsyncWorker */<br>            $apiAsyncWorker = new $workerClass(<br>                handler: [get_class($controller), $method],<br>                arguments: array_values($parameters),<br>                request: $request<br>            );<br><br>            // Dispatch the worker and return the response<br>            return $apiAsyncWorker-&gt;dispatch();<br>        }<br><br>        // If the method does not have the Async attribute, proceed as usual<br>        return parent::dispatch($route, $controller, $method);<br>    }<br><br>    /**<br>     * @noinspection PhpDocSignatureInspection<br>     * @template TAttribute<br>     * @param TAttribute $attribute<br>     * @return ?TAttribute<br>     * @throws ReflectionException<br>     */<br>    public function getControllerMethodAttribute($controller,string $method,string $attribute): ?object<br>    {<br>        $reflection = new ReflectionMethod($controller,$method);<br><br>        $attribute = $reflection-&gt;getAttributes($attribute)[0] ?? null;<br><br>        return $attribute?-&gt;newInstance();<br>    }<br>}</pre><h3>Step 6: Overriding ControllerDispatcher in AppServiceProvider</h3><p>In the AppServiceProvider, we override the default ControllerDispatcher with our custom ControllerDispatcher.</p><pre>&lt;?php<br><br>namespace App\Providers;<br><br>use App\Overrides\Routing\ControllerDispatcher;<br>use Illuminate\Support\ServiceProvider;<br><br>class AppServiceProvider extends ServiceProvider <br>{<br>    protected function register(): void <br>    {<br>        $this-&gt;app-&gt;singleton(<br>            \Illuminate\Routing\Contracts\ControllerDispatcher::class,<br>            ControllerDispatcher::class<br>        );<br>    }<br>}</pre><h3>Usage Example</h3><p>Now, we can use the Async attribute in our controllers to mark the methods that should be processed asynchronously.</p><pre>&lt;?php<br><br>namespace App \Http\Controllers;<br><br>use App\Support\Api\Workers\ExampleWorker;<br>use App\Support\Api\Attributes\Async;<br><br><br>class ExampleController extends Controller<br>{<br>   #[Async (workerClass: ExampleWorker::class)]<br>   public function heavyProcessHandler () : mixed<br>   {<br>       // Heavy processing code..<br>   }<br>}</pre><h3>Summary</h3><p>By integrating PHP 8 attributes, creating a structured simple asynchronous worker system, and extending Laravel’s ControllerDispatcher, we have developed a flexible and efficient asynchronous API handler in Laravel. This approach allows developers to easily mark methods for asynchronous execution, making the application more responsive and providing a seamless user experience. The unique processId returned in the response can be used to poll or notify the client once the processing is completed, offering a structured and maintainable way to manage asynchronous tasks in Laravel applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca5597684d3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>