<?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 Saman Esmaeil on Medium]]></title>
        <description><![CDATA[Stories by Saman Esmaeil on Medium]]></description>
        <link>https://medium.com/@teal33t?source=rss-7f2339b3b56b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WxSe50E4y800C27pyN6LoQ.jpeg</url>
            <title>Stories by Saman Esmaeil on Medium</title>
            <link>https://medium.com/@teal33t?source=rss-7f2339b3b56b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:49:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@teal33t/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[torget.py: I Built a Tool to Fix My Biggest Frustration with Tor Network]]></title>
            <link>https://medium.com/@teal33t/torget-py-i-built-a-tool-to-fix-my-biggest-frustration-with-tor-network-a771b49e1dea?source=rss-7f2339b3b56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a771b49e1dea</guid>
            <category><![CDATA[tor-network]]></category>
            <category><![CDATA[tor]]></category>
            <category><![CDATA[darkweb]]></category>
            <category><![CDATA[tor-browser]]></category>
            <category><![CDATA[hidden-services]]></category>
            <dc:creator><![CDATA[Saman Esmaeil]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 08:21:50 GMT</pubDate>
            <atom:updated>2025-10-11T08:26:15.891Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFqcHZ9b_JUCFdq0DeDJaQ.png" /></figure><p>The Tor network, often lauded as the gold standard for online anonymity and privacy, presents a fascinating paradox. It offers a sanctuary for free expression, a shield against surveillance, and a means to bypass censorship, yet it frequently frustrates users with its notoriously slow performance, especially when it comes to downloading files.</p><p>This article delves into the fundamental reasons behind Tor’s inherent latency, explores general strategies to mitigate these slowdowns, and introduces <a href="https://github.com/teal33t/torget.py"><strong>torget.py</strong></a>, a specialized tool engineered to optimize the downloading experience within the unique constraints of the Tor ecosystem.</p><p><strong>Tor and the Onion Protocol: A Deep Dive into Anonymity</strong></p><p>At its core, Tor, an acronym for The Onion Router, is a free and open-source software project that enables anonymous communication. Its primary purpose is to protect users’ privacy and freedom online by making it difficult to trace their internet activity back to them. This is achieved through a sophisticated routing technique known as the <strong>Onion Protocol</strong>.</p><p>Imagine an onion: it has multiple layers. Similarly, when you use Tor, your internet traffic is encrypted in multiple layers. This layered encryption is the cornerstone of the Onion Protocol. Your data is first encrypted by your Tor client, then wrapped in several more layers of encryption, each intended for a different relay in the Tor network.</p><p>This multi-layered encryption ensures that no single relay knows both the origin and the final destination of your data.</p><p>Your traffic then traverses a decentralized network of volunteer-operated servers, known as <strong>relays</strong>.</p><p>Typically, a Tor circuit consists of at least three relays: an <strong>entry guard</strong> (the first relay your traffic hits), a <strong>middle relay</strong>, and an <strong>exit relay</strong> (the final relay before your traffic reaches its destination on the public internet).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*tmwunGYcn4WRvJAV.png" /></figure><p>Each relay peels off one layer of encryption, revealing only the address of the next relay in the circuit, but never the complete path. This ingenious design masks your IP address and location, making it incredibly difficult for observers to track your online activities, thereby providing strong anonymity and resistance to censorship.</p><p><strong>The Price of Privacy: Why Tor is Inherently Slow</strong></p><p>While Tor’s architecture is a triumph for privacy, it comes at a significant performance cost. The very mechanisms that guarantee anonymity are also responsible for its perceived slowness.</p><p>Understanding these factors is crucial to appreciating the challenges and solutions in optimizing Tor usage:</p><p>1. <strong>Multi-Hop Routing:</strong> Every piece of data you send through Tor must travel through at least three relays, often located in different parts of the world. Each hop involves a cryptographic operation (decryption and re-encryption) and network latency as data traverses physical distances. This sequential processing at multiple points inherently adds delays, making the connection feel sluggish compared to a direct internet connection.</p><p>2. <strong>Volunteer-Operated Relays:</strong> The backbone of the Tor network is its global community of volunteers who donate their bandwidth and computing resources to run relays. The quality and speed of these relays vary dramatically. Some might be high-bandwidth servers, while others could be running on older hardware with limited internet connections. A single slow relay in a circuit can bottleneck the entire connection, significantly impacting data transfer rates.</p><p>3. <strong>Network Congestion:</strong> Tor serves a vast user base, with over a million daily users relying on a network of just over 6,000 relays. This high demand, coupled with the finite resources of volunteer relays, often leads to network congestion. During peak usage times, traffic competes for limited bandwidth, exacerbating slowdowns and increasing latency [4].</p><p>4. <strong>Geographic Distance:</strong> The decentralized nature of Tor means that the relays forming your circuit can be geographically dispersed across continents. Data traveling thousands of miles naturally incurs higher latency due to the physical limitations of signal propagation and the numerous internet service providers (ISPs) it must traverse. This geographical diversity, while enhancing anonymity, directly contributes to slower speeds.</p><p>5. <strong>Exit Node Bottlenecks:</strong> Exit relays are particularly critical as they are the gateway from the Tor network to the public internet. They are often the most heavily utilized and can become a significant bottleneck. The limited number of exit nodes, combined with their varying capacities and potential for abuse (which can lead to them being blocked by websites), can severely impact download speeds and overall browsing experience.</p><p><strong>General Strategies to Improve Tor Speed (and their limitations)</strong></p><p>While the fundamental design of Tor prioritizes anonymity over speed, there are some general approaches users can take to potentially improve their experience, though these often come with limitations:</p><ul><li><strong>Choosing Faster Entry Guards/Bridges:</strong> Some users might try to find and configure faster entry guards or bridges, but this requires a degree of technical expertise and consistent monitoring, as relay speeds can change.</li><li><strong>Avoiding Peak Hours:</strong> Using Tor during off-peak hours when network congestion is lower can sometimes yield better speeds, but this is not always practical or feasible for users.</li><li><strong>Optimizing Local Resources:</strong> Ensuring your local machine has sufficient CPU, RAM, and a stable internet connection can help, but these optimizations only address client-side bottlenecks, not the inherent network limitations.</li><li><strong>Disabling SSL Verification</strong>: While disabling SSL verification does make you vulnerable to man-in-the-middle attacks, but disabling it makes downloads faster by skipping the SSL certificate verification process, which can be particularly slow over Tor. When SSL verification is enabled, your client must verify the authenticity of the server’s certificate, which involves additional network requests and cryptographic operations. In the context of Tor, these verification steps can add significant latency to each connection.</li></ul><p>Ultimately, these general strategies offer marginal improvements. The core architectural trade-offs between anonymity and speed remain, meaning that Tor will always be slower than a direct, unencrypted internet connection.</p><p><strong>Introducing </strong><strong>torget.py: A Specialized Approach to Faster Tor Downloads</strong></p><p>Recognizing that traditional download tools are not built to navigate the unique challenges of the Tor network, I developed torget.pyas a specialized, multi-threaded downloader.</p><p>Its design focuses on optimizing the downloading experience <em>within</em> the privacy-preserving framework of Tor, rather than trying to circumvent it. The project aims to make bulk data transfers over Tor as efficient as possible by intelligently leveraging its features:</p><p><strong>Multi-threaded Downloads</strong></p><p>Unlike standard downloaders that typically use a single connection, torget.py employs multiple worker threads. This approach is particularly effective on the Tor network because:</p><ul><li><strong>Parallel Circuit Utilization:</strong> When configured with multiple Tor SOCKS5 proxies, each worker thread can potentially establish its own independent Tor circuit. This means that if one circuit is slow or congested, other threads might be utilizing faster, less burdened circuits, allowing the download to proceed more efficiently in parallel.</li><li><strong>Distributed Load:</strong> By splitting the download task across several threads, torget.py can distribute the load across different Tor relays and circuits, preventing any single circuit from becoming an overwhelming bottleneck. This parallelization can significantly increase the overall throughput, even if individual circuits remain slow.</li></ul><p><strong>Optimized Session Configuration with Retries</strong></p><p>torget.py utilizes requests.Session with an HTTPAdapter that is specifically tuned for resilience and efficiency on an unpredictable network like Tor. This includes:</p><ul><li><strong>Connection Pooling:</strong> Reusing established TCP connections for multiple requests to the same host reduces the overhead of repeatedly setting up new connections, thereby lowering latency and improving efficiency.</li><li><strong>Robust Retry Strategy:</strong> The script is configured with an aggressive retry strategy for transient network errors (e.g., HTTP 429 Too Many Requests, 5xx server errors). This allows torget.py to automatically recover from temporary network glitches or overloaded relays without failing the entire download, making it more robust against Tor’s inherent instability.</li><li><strong>Increased Pool Connections and Max Size:</strong> The HTTP adapter’s pool_connections and pool_maxsize are set to higher values (20 and 50, respectively). This allows the session to maintain a larger pool of active and idle connections, which is crucial for supporting multiple worker threads and managing diverse Tor circuits effectively.</li></ul><p><strong>Support for Multiple Tor Proxies</strong></p><p>One of `torget.py`’s most powerful features is its ability to accept a list of Tor SOCKS5 proxy addresses via the ` — proxy-list` command-line argument. This enables a crucial optimization:</p><p><strong>Circuit Diversity and Load Balancing:</strong> By rotating through a list of proxies, each worker thread can initiate its connection through a different entry point into the Tor network. This strategy helps to bypass particularly slow or congested circuits and effectively balances the load across available Tor resources. If you have multiple Tor instances running (e.g., Tor Browser instances configured to expose different SOCKS ports), torget.py can leverage all of them simultaneously.</p><p>The complete source code for torget.py is available on my GitHub repository. You can access the source code at:</p><p><a href="https://github.com/teal33t/torget.py">https://github.com/teal33t/torget.py</a></p><p>Feel free to explore the repository, report issues, or contribute to the development of torget.py. The project is open-source and welcomes community input to further enhance Tor downloading capabilities.</p><p>Keep in mind, It’s not about making Tor as fast as the clearnet, but about making Tor downloads <em>as fast as they can be.</em></p><p>On the next post I will explain how to configure a <em>fast as it can </em>Tor node.</p><p>Follow me on medium: https://medium.com/@teal33t</p><p>Follow me on github: <a href="https://github.com/teal33t">https://github.com/teal33t</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a771b49e1dea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should You Build a Data Warehouse for your Company?]]></title>
            <link>https://medium.com/analytics-vidhya/should-you-build-a-data-warehouse-for-your-company-7d2ae0e49701?source=rss-7f2339b3b56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d2ae0e49701</guid>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[warehouse-automation]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Saman Esmaeil]]></dc:creator>
            <pubDate>Sat, 08 Mar 2025 18:22:17 GMT</pubDate>
            <atom:updated>2025-03-08T18:22:49.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ATjf0ZHtk-LCudMq4dDh5w.jpeg" /></figure><p>This question marks a significant milestone in an organization’s analytical journey. It often emerges when teams find themselves manually crafting dashboards or spreadsheets repeatedly, grappling with growing data volumes, or feeling overwhelmed by the fear of missing out (FOMO) after reading too many data-related articles.</p><p>However, deciding to build a data warehouse is not a decision to take lightly. Not every organization needs one, and there are valid reasons both for and against it. In this article, we’ll explore what a data warehouse is, its benefits, its use cases, reasons you might not need one, and alternative options to consider if a full-fledged data warehouse isn’t the right fit.</p><p><strong>What is a Data Warehouse?</strong></p><p>To decide whether a data warehouse is necessary, we first need to understand what it is. <a href="https://en.wikipedia.org/wiki/Bill_Inmon">Bill Inmon</a>, a pioneer in data management, defines a data warehouse as “a subject-oriented, integrated, time-variant, non-volatile collection of data in support of management’s decision-making process.”</p><p>Let’s unpack this:</p><ul><li><strong>Subject-Oriented:</strong> Data is organized around key business subjects like sales, customers, or products, making it easier to analyze specific areas.</li><li><strong>Integrated:</strong> It combines data from various sources — finance, marketing, operations — into a unified view.</li><li><strong>Time-Variant:</strong> It stores historical data, enabling analysis over time, unlike many operational systems that only show the current state.</li><li><strong>Non-Volatile:</strong> Once data is entered, it remains unchanged, providing a stable foundation for decision-making.</li></ul><p>Essentially, a data warehouse centralizes data, integrates it across disparate sources, and adds historical context to support actionable insights. It’s not just about storage — it’s about enabling management to make informed decisions.</p><p><strong>Benefits of a Data Warehouse</strong></p><p>A data warehouse offers several compelling advantages, especially for organizations managing complex data environments. Here are the key benefits:</p><p><strong>1. Accessibility</strong></p><p>Data in operational systems is often scattered, requiring manual extraction or complex querying that’s challenging for non-technical users.</p><p>A data warehouse centralizes this data into one accessible location and remodels it into an intuitive format, such as the fact-dimension model.</p><p>Fact tables hold core metrics (e.g., sales totals), while dimension tables provide context (e.g., time, location), simplifying analysis for analysts and reducing the hassle of joining data from 30 different Excel downloads.</p><p><strong>2. Historical Tracking</strong></p><p>Operational systems typically overwrite old data — like a customer’s previous address — making historical analysis impossible.</p><p>A data warehouse preserves this history, tracking changes over time (e.g., via slowly changing dimensions or daily snapshots).</p><p>This allows for accurate analyses, such as how customer spending varies by location year over year, even if their address changes.</p><p><strong>3. Data Integration</strong></p><p>Integrating data from multiple sources — Salesforce, HubSpot, or internal systems — can be chaotic, with inconsistent keys like email or customer ID leading to mismatched results.</p><p>A data warehouse standardizes this process during its ETL (extract, transform, load) phase, creating a consistent integration layer.</p><p>This ensures everyone gets the same answers to cross-departmental questions, avoiding the mess of ad-hoc joins on unreliable fields like first and last names.</p><p><strong>4. Automation</strong></p><p>Manual reporting — downloading data, cleaning it, and building reports — is time-consuming and error-prone.</p><p>A data warehouse automates this by centralizing data and scheduling refreshes, freeing up time and ensuring reports are based on the latest information.</p><p>This is especially valuable for organizations needing frequent, reliable updates without constant manual intervention.</p><p><strong>Use Cases for a Data Warehouse</strong></p><p>Data warehouses support a variety of practical applications, making them versatile tools for data-driven organizations. Here are the main use cases:</p><p><strong>1. Reporting and Dashboarding</strong></p><p>The most common use is building reports and dashboards, from simple metrics to complex visualizations in tools like Tableau.</p><p>A centralized data warehouse ensures consistency across these outputs, making it easier to track performance or share insights organization-wide.</p><p><strong>2. Automating Decisions</strong></p><p>Data warehouses can go beyond reporting to automate small-scale decisions.</p><p>For example, if a dashboard shows ad spend should increase based on a metric, the warehouse could eventually trigger that action automatically.</p><p>This removes the human from routine decision loops, streamlining processes like budget adjustments.</p><p><strong>3. Machine Learning and Data Science</strong></p><p>While raw data lakes often fuel advanced analytics, data warehouses provide clean, structured data for machine learning and data science.</p><p>Teams can build feature tables or datasets directly from the warehouse, trusting its accuracy due to quality checks and deduplication.</p><p>This reliability makes it a solid foundation for training models or forecasting trends.</p><p><strong>Why You Might Not Need a Data Warehouse</strong></p><p>Despite its advantages, a data warehouse isn’t always the right choice. Here’s why it might not suit your needs:</p><p><strong>1. Infrequent or Simple Reporting</strong></p><p>If reporting happens only once a month or week and takes minimal effort (e.g., an hour), a data warehouse could be overkill.</p><p>The time saved by automation may not justify the significant investment required.</p><p><strong>2. Cost Considerations</strong></p><p>Building and maintaining a data warehouse is expensive. Hiring a data engineer or architect can cost upwards of $150,000 annually, plus technology costs ranging from $30,000 to $100,000+ depending on data volume.</p><p>For small companies or tight budgets, this price tag may outweigh the benefits.</p><p><strong>3. Alternatives for Smaller Needs</strong></p><p>Simpler tools can suffice for basic needs. Solutions like Tinybird or Rockset allow direct querying of data sources without a full warehouse, while Excel or direct Tableau connections might work for small-scale reporting.</p><p>These options avoid the complexity and cost of a warehouse while still answering key questions.</p><p><strong>Decision Factors: Should You Build a Data Warehouse?</strong></p><p>The choice to build a data warehouse hinges on your organization’s specific circumstances. Consider these factors:</p><ul><li><strong>Data Volume and Sources:</strong> Are you handling large, messy datasets from multiple systems? A warehouse excels at managing complexity.</li><li><strong>Reporting Frequency:</strong> Does frequent, manual reporting drain resources? Automation via a warehouse could help.</li><li><strong>Budget:</strong> Can you afford the staff (e.g., data engineers) and tech stack? Costs escalate quickly.</li><li><strong>Data Complexity:</strong> Do inconsistent formats or integration challenges hinder analysis? A warehouse standardizes this.</li><li><strong>Analytical Goals:</strong> Are historical trends or advanced analytics critical? If not, simpler tools might do.</li></ul><p>Here’s a quick checklist:</p><ul><li><strong>Multiple data sources needing integration?</strong></li><li><strong>Historical data essential for insights?</strong></li><li><strong>Significant time spent on manual reporting?</strong></li><li><strong>Budget for staff and technology?</strong></li><li><strong>Unanswered business questions due to current limitations?</strong></li></ul><p>If most answers are “yes,” a data warehouse makes sense. If “no,” explore lighter alternatives.</p><p><strong>Should You Build a Data Warehouse for your Company?</strong></p><p>A data warehouse can transform how an organization handles data, offering accessibility, historical tracking, integration, and automation that empower better decisions. Its use cases — reporting, decision automation, and data science — make it a cornerstone for analytically mature companies.</p><p>However, it’s not a universal solution. Small teams with simple, infrequent reporting needs or limited budgets may find the costs outweigh the gains, especially with alternatives like Tinybird, Rockset, or even Excel available. Before diving in, assess your data volume, reporting demands, and resources.</p><p>A data warehouse is a powerful tool, but only if it aligns with your needs — otherwise, simpler options can keep you moving forward without the heavy lift.</p><p><em>If you found this information helpful and want to delve deeper into data warehousing, analytics, and related topics, be sure to follow me on Medium </em><a href="https://medium.com/@teal33t"><em>@teal33t</em></a><em> for more in-depth articles, practical tips, and insightful perspectives. Let’s continue the conversation and learn together in the ever-evolving world of data!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d2ae0e49701" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/should-you-build-a-data-warehouse-for-your-company-7d2ae0e49701">Should You Build a Data Warehouse for your Company?</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Strategy and Chain of Responsibility are everywhere in Symfony Components]]></title>
            <link>https://medium.com/@teal33t/why-strategy-and-chain-of-responsibility-are-everywhere-in-symfony-components-5c52f53a8b66?source=rss-7f2339b3b56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c52f53a8b66</guid>
            <category><![CDATA[php-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[symfony-framework]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Saman Esmaeil]]></dc:creator>
            <pubDate>Fri, 14 Feb 2025 18:24:15 GMT</pubDate>
            <atom:updated>2025-02-14T18:27:37.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0HK2xNNgwLT9uBdm8bk0Q.png" /></figure><p>Design patterns are the backbone of maintainable and scalable software. In the Symfony ecosystem, two patterns stand out for their frequent and powerful collaboration:</p><p><strong>Strategy Pattern</strong> and <strong>Chain of Responsibility Pattern</strong>.</p><p>These patterns are used in components like Mailer, Messenger, Notifier, and Security to create flexible, decoupled, and easy-to-maintain code. Let’s explore how combining these patterns unlocks their full potential and why Symfony developers swear by them.</p><h3>Understanding the Strategy Pattern</h3><p>The Strategy Pattern allows you to define a family of interchangeable algorithms and select one at runtime. Here’s a simplified example:</p><p><strong>1. Define a Strategy Interface</strong>:</p><pre>interface StrategyInterface {<br>    public function execute(array $numbers): float;<br>}</pre><p>2. <strong>Implement Concrete Strategies</strong>:</p><pre>class AddStrategy implements StrategyInterface {<br>    public function execute(array $numbers): float {<br>        return array_sum($numbers);<br>    }<br>}<br><br>class SubtractStrategy implements StrategyInterface {<br>    public function execute(array $numbers): float {<br>        return array_reduce($numbers, fn($carry, $num) =&gt; $carry - $num, 0);<br>    }<br>}</pre><p>3. <strong>Context Class to Execute Strategies</strong>:</p><pre>class Example {<br>    public function executeStrategy(StrategyInterface $strategy, array $numbers): float {<br>        return $strategy-&gt;execute($numbers);<br>    }<br>}</pre><pre>$example = new Example();<br>echo $example-&gt;executeStrategy(new AddStrategy(), [5, 3, 5]); // 13<br>echo $example-&gt;executeStrategy(new SubtractStrategy(), [5, 3, 5]); // -13</pre><p>Here, strategies are swapped based on the desired behavior.</p><h3>Introducing the Chain of Responsibility</h3><p>The Chain of Responsibility pattern lets you pass requests along a chain of handlers. Each handler decides whether to process the request or pass it to the next handler. To combine it with the Strategy Pattern:</p><ol><li><strong>Modify the Strategy Interface</strong>:<br>Add a supports() method to determine which strategy applies.</li></ol><pre>interface StrategyInterface {<br>    public function supports(string $type): bool;<br>    public function execute(array $numbers): float;<br>}</pre><p>2. <strong>Update Concrete Strategies</strong>:</p><pre>class AddStrategy implements StrategyInterface {<br>    public function supports(string $type): bool {<br>        return $type === &#39;add&#39;;<br>    }<br>    // execute() remains the same<br>}<br><br>class SubtractStrategy implements StrategyInterface {<br>    public function supports(string $type): bool {<br>        return $type === &#39;subtract&#39;;<br>    }<br>    // execute() remains the same<br>}</pre><p>3. <strong>Refactor the Context Class</strong>:</p><pre>class Example {<br>    private array $strategies;<br><br>    public function __construct(array $strategies) {<br>        $this-&gt;strategies = $strategies;<br>    }<br><br>    public function executeStrategies(string $type, array $numbers): float {<br>        foreach ($this-&gt;strategies as $strategy) {<br>            if ($strategy-&gt;supports($type)) {<br>                return $strategy-&gt;execute($numbers);<br>            }<br>        }<br>        throw new \InvalidArgumentException(&#39;No strategy found.&#39;);<br>    }<br>}</pre><pre>$example = new Example([new AddStrategy(), new SubtractStrategy()]);<br>echo $example-&gt;executeStrategies(&#39;add&#39;, [5, 3, 5]); // 13</pre><p>Now, the context iterates through strategies, using the first one that “supports” the request. Adding a new strategy is as simple as including it in the constructor — <strong>no existing code needs modification</strong>.</p><h3>Real-World Symfony Examples</h3><p>Symfony leverages this combination extensively:</p><ol><li><strong>Mailer &amp; Notifier Components</strong>:<br>The Transport class uses a chain of transport factories. Each factory’s supports() method checks if it can handle a DSN string. Only the matching factory creates the transport.</li><li><strong>Serializer Component</strong>:<br>Encoders/Decoders are evaluated via supportsEncoding() or supportsDecoding(). The first compatible encoder/decoder in the chain is selected.</li><li><strong>Security Component</strong>:<br>The AuthenticatorManager iterates over authenticators. Each authenticator’s supports() method determines if it can handle the request (e.g., form login vs. API token).</li></ol><h3>Benefits of the Combined Approach</h3><ol><li><strong>Flexibility</strong>: Swap or add strategies without altering existing code (Open/Closed Principle).</li><li><strong>Decoupling</strong>: Strategies don’t need to know about each other.</li><li><strong>Maintainability</strong>: Clear separation of concerns makes debugging easier.</li><li><strong>Scalability</strong>: New behaviors are added by introducing new strategy classes.</li></ol><p>The marriage of the Strategy and Chain of Responsibility patterns is a game-changer for writing clean, modular code. By letting each strategy decide its applicability, Symfony components achieve remarkable extensibility and simplicity. Next time you use the Mailer or Security component, remember: under the hood, these two patterns are working in harmony to keep your code elegant and efficient.</p><p><em>Have you ? Share your experiences in the comments! 🚀</em></p><p><em>If you enjoyed learning how Symfony leverages design patterns for clean architecture, you might love my deep dive into </em><a href="https://medium.com/@teal33t/clean-code-in-php-best-practices-and-principles-8ccf2f1673a7"><strong><em>“Clean Code in PHP: Best Practices and Principles”</em></strong></a><strong><em> or </em></strong><em>“</em><a href="https://medium.com/@teal33t/9-tips-for-building-and-developing-secure-php-923b65ec0298"><strong><em>9 Tips for Building and Developing Secure PHP</em></strong></a><em>”.</em></p><p><strong><em>Follow me for further readings!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c52f53a8b66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[9 Tips for Building and Developing Secure PHP]]></title>
            <link>https://systemweakness.com/9-tips-for-building-and-developing-secure-php-923b65ec0298?source=rss-7f2339b3b56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/923b65ec0298</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[php-developers]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[php-8]]></category>
            <category><![CDATA[secure-development]]></category>
            <dc:creator><![CDATA[Saman Esmaeil]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 18:52:52 GMT</pubDate>
            <atom:updated>2025-02-17T11:33:33.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2R7HM5qznGYF5sa1.png" /></figure><p>Even seasoned developers face unexpected challenges — malformed data from a third-party API, a user inputting bizarre strings, or a silent failure that cascades into a security flaw. In PHP, where flexibility reigns, prioritizing security isn’t optional; it’s foundational.</p><p>Secure coding isn’t just about patching vulnerabilities. It’s a mindset: anticipating risks, designing safeguards, and ensuring your application remains robust under pressure. Below are actionable strategies to fortify your PHP projects against common threats.</p><h3>1. Secure Dependencies with Composer and Version Pinning</h3><p>Third-party libraries are a double-edged sword: they save time but introduce risks if outdated or unmaintained. Use Composer to manage dependencies, and <em>pin versions</em> to avoid unintended updates that might introduce vulnerabilities.</p><p>Enable Composer’s composer audit command (PHP 8.2+) to scan for known vulnerabilities:</p><pre>composer audit</pre><p>Additionally, lock dependencies to specific versions in composer.json:</p><pre>&quot;require&quot;: {<br>    &quot;monolog/monolog&quot;: &quot;2.8.0&quot; // Avoid wildcards like &quot;2.8.*&quot;<br>}</pre><p>Regularly update packages using composer update --dry-run to review changes before applying them.</p><h3>2. Harden Session Management</h3><p>PHP’s default session handling is notoriously insecure. Mitigate session hijacking and fixation risks by:</p><ul><li><strong>Regenerating session IDs</strong> after login.</li><li><strong>Setting secure cookie attributes</strong> (HTTPS-only, SameSite flags).</li><li><strong>Storing sessions in a secure location</strong> (database or encrypted files).</li></ul><p>Example configuration:</p><pre>session_start([<br>    &#39;cookie_secure&#39; =&gt; true,    // Transmit only over HTTPS<br>    &#39;cookie_samesite&#39; =&gt; &#39;Strict&#39;,<br>    &#39;cookie_httponly&#39; =&gt; true  // Prevent JavaScript access<br>]);<br><br>// Regenerate ID after authentication<br>session_regenerate_id(true);</pre><h3>3. Implement CSRF Protection Globally</h3><p>Cross-Site Request Forgery (CSRF) attacks trick users into executing unintended actions. Defend against them by:</p><ul><li>Generating unique tokens for forms.</li><li>Validating tokens server-side before processing requests.</li></ul><pre>class CSRFGuard {<br>    public static function generateToken(): string {<br>        if (empty($_SESSION[&#39;csrf_token&#39;])) {<br>            $_SESSION[&#39;csrf_token&#39;] = bin2hex(random_bytes(32));<br>        }<br>        return $_SESSION[&#39;csrf_token&#39;];<br>    }<br>    public static function validateToken(string $token): void {<br>        if (!hash_equals($_SESSION[&#39;csrf_token&#39;], $token)) {<br>            throw new RuntimeException(&quot;CSRF token validation failed.&quot;);<br>        }<br>    }<br>}<br><br>// Usage in forms:<br>&lt;input type=&quot;hidden&quot; name=&quot;csrf_token&quot; value=&quot;&lt;?= CSRFGuard::generateToken() ?&gt;&quot;&gt;</pre><h3>4. Sanitize and Validate Every Input</h3><p>Assume every piece of data entering your application is malicious until proven otherwise. From form submissions to API payloads, rigorous validation prevents injection attacks and data corruption.</p><p>For example, when handling user registration:</p><pre>function validateUserEmail(string $email): string {<br>    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {<br>        throw new InvalidArgumentException(&quot;Invalid email format.&quot;);<br>    }<br>    return htmlspecialchars($email, ENT_QUOTES, &#39;UTF-8&#39;);<br>}</pre><p>Here, we validate the email format <em>and</em> escape HTML characters to thwart XSS attacks.</p><h3>2. Enforce Strict Type Declarations</h3><p>PHP’s loose typing can introduce subtle bugs. By enforcing strict types, you eliminate ambiguity and reduce risks like unintended type juggling.</p><p>Enable strict mode and define parameter/return types:</p><pre>declare(strict_types=1);<br>function applyDiscount(float $price, int $discountPercent): float {<br>    return $price - ($price * ($discountPercent / 100));<br>}</pre><p>Passing a string to $discountPercent now triggers an immediate error, preventing miscalculations.</p><h3>3. Use Prepared Statements for Database Interactions</h3><p>SQL injection remains a top threat. Avoid concatenating user input into queries. Instead, use PDO or MySQLi with prepared statements:</p><pre>$stmt = $pdo-&gt;prepare(&quot;SELECT * FROM users WHERE username = :username&quot;);<br>$stmt-&gt;execute([&#39;username&#39; =&gt; $userInput]);<br>$user = $stmt-&gt;fetch();</pre><p>This ensures user input is treated as data, not executable code.</p><h3>4. Implement Error Handling That Hides Sensitive Data</h3><p>Avoid exposing stack traces or server details to users. Customize error messages and log issues internally:</p><pre>try {<br>    $email = validateUserEmail($_POST[&#39;email&#39;]);<br>} catch (InvalidArgumentException $e) {<br>    error_log(&quot;Registration error: &quot; . $e-&gt;getMessage());<br>    displayUserError(&quot;Please provide a valid email address.&quot;);<br>}</pre><p>Never reveal system details in client-facing messages — attackers can exploit them.</p><h3>5. Encapsulate Sensitive Operations</h3><p>Keep security-critical logic isolated. For instance, password hashing should be centralized to avoid inconsistencies:</p><pre>class AuthHandler {<br>    public function hashPassword(string $password): string {<br>        return password_hash($password, PASSWORD_DEFAULT);<br>    }<br>    public function verifyPassword(string $password, string $hash): bool {<br>        return password_verify($password, $hash);<br>    }<br>}</pre><p>This ensures password handling follows best practices across your app.</p><h3>6. Test for Security, Not Just Functionality</h3><p>Traditional unit tests often miss security flaws. Adopt tools like PHPStan for static analysis, or write tests targeting edge cases:</p><pre>public function testSqlInjectionAttempt(): void {<br>    $userInput = &quot;admin&#39;; DROP TABLE users;--&quot;;<br>    $result = $this-&gt;authHandler-&gt;login($userInput, &#39;password123&#39;);<br>    $this-&gt;assertFalse($result); // Ensure invalid input is rejected<br>}</pre><p>Proactively simulate attacks to uncover weaknesses.</p><h3>Final Thoughts</h3><p>Writing secure PHP isn’t about perfection — it’s about reducing risk at every layer. Start by auditing your code for unfiltered inputs, loose type comparisons, and raw SQL queries. Gradually integrate these practices, and prioritize security-focused tools in your workflow.</p><h3>Secure Code is Clean Code: Bridging the Gap</h3><p>While the practices above focus on hardening your PHP applications against threats, security doesn’t exist in a vacuum. Writing secure code goes hand-in-hand with writing <em>clean</em> code. A well-structured, readable codebase isn’t just easier to maintain — it’s also easier to audit for vulnerabilities and less prone to hidden risks.</p><p>In my previous article, <a href="https://medium.com/@teal33t/clean-code-in-php-best-practices-and-principles-8ccf2f1673a7"><strong>Clean Code in PHP: Best Practices and Principles</strong></a>, I dive into strategies for clean code in PHP. Check it out!</p><p>What’s your go-to strategy for securing PHP apps? Share your approach in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=923b65ec0298" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/9-tips-for-building-and-developing-secure-php-923b65ec0298">9 Tips for Building and Developing Secure PHP</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jyotish API — Free and Open Source Self-hosted Vedic Astrology API]]></title>
            <link>https://medium.com/@teal33t/jyotish-api-free-and-open-source-self-hosted-vedic-astrology-api-1795e7437555?source=rss-7f2339b3b56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1795e7437555</guid>
            <category><![CDATA[horoscopes]]></category>
            <category><![CDATA[astrology-services]]></category>
            <category><![CDATA[astrology]]></category>
            <category><![CDATA[jyotish]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Saman Esmaeil]]></dc:creator>
            <pubDate>Sun, 09 Feb 2025 19:44:00 GMT</pubDate>
            <atom:updated>2025-02-09T19:59:09.765Z</atom:updated>
            <content:encoded><![CDATA[<h3>Jyotish API — Free and Open Source Self-hosted Vedic Astrology API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6c2upBfdjD4x1OF9C0U1BQ.jpeg" /></figure><p>Vedic astrology, or Jyotish, is an ancient system of celestial science that has been practiced for thousands of years. With the advent of modern technology, the ability to perform complex astrological calculations programmatically has become increasingly valuable.</p><p>The <a href="https://github.com/teal33t/jyotish-api">Jyotish API</a> is a sophisticated self-hosted REST-based service that bridges the gap between ancient Vedic astrology and modern software development. Built on top of the well-established `kunjara/jyotish` library, this API provides developers with seamless access to a wide range of astrological calculations. The API’s containerized architecture ensures easy deployment and scalability, making it a powerful tool for both hobbyists and professionals.</p><p>This article delves into the technical architecture, key features, implementation details, challenges, and best practices associated with the <a href="https://github.com/teal33t/jyotish-api">Jyotish API</a>. By the end of this deep dive, you’ll have a comprehensive understanding of how to use, deploy, and extend a Vedic astrology API for modern applications.</p><h3>Installation and Build</h3><p>To install and build the Jyotish API utilizes Docker and provides clear instructions for integrating the Swiss Ephemeris.</p><p>Commands for cloning, building and running the API:</p><pre>git clone git@github.com:teal33t/jyotish-api.git<br>cd jyotish-api<br>docker-compose up --build -d<br>docker-compose exec jyotish_api bash -c &quot;cd swetest/src &amp;&amp; make&quot;</pre><p>These commands set up the Docker container, build the application, and compile the Swiss Ephemeris within the container, ensuring that all components are correctly configured.</p><p>Now open: <a href="http://localhost:9393/api/ping,">http://localhost:9393/api/ping</a> , It’s ready!</p><h3>Core Components</h3><p>The Jyotish API’s capabilities are extensive, covering the breadth of Vedic astrological calculations.</p><h3>Astronomical Calculations Engine</h3><ul><li><strong>Integration with Swiss Ephemeris for Precise Planetary Positions :</strong> Leveraging the Swiss Ephemeris ensures that all planetary positions are calculated with high accuracy. This precision is vital for generating reliable astrological charts and interpretations.</li><li><strong>Implementation of Ayanamsha Calculations (Precession Adjustments) :</strong> Ayanamsha refers to the longitudinal difference between the tropical (Western) and sidereal (Vedic) zodiacs. The API implements various Ayanamsha systems to adjust for the precession of the equinoxes, aligning calculations with traditional Vedic methods.</li><li><strong>Support for Multiple Coordinate Systems and Time Zones : </strong>The API accommodates various geographic coordinate systems and time zones, allowing users worldwide to obtain accurate astrological data pertinent to specific locations and times.</li></ul><h3>Chart Calculation System</h3><ul><li><strong>Implementation of 16 Varga (Divisional) Charts</strong> : Varga charts are divisional charts used in Vedic astrology to provide deeper insights into various aspects of life. The API computes all 16 classical Varga charts, offering comprehensive astrological analyses.</li></ul><p>Planetary Position Calculations Including :</p><ul><li><strong>Longitude, Latitude, and Speed</strong> : Calculates the precise position and motion of celestial bodies.</li><li><strong>Declination and Ascension</strong> : Determines the celestial coordinates used in plotting astrological charts.</li><li><strong>Nakshatra (Lunar Mansion) Positions</strong> : Identifies the moon’s position within the 27 Nakshatras, fundamental in Vedic astrology.</li></ul><h4>API Layer</h4><ul><li><strong>REST API Implementation Using Symfony Framework : </strong>The API is developed using the Symfony framework, a set of reusable PHP components and a PHP framework for web projects. Symfony provides a robust foundation for building scalable web services, offering features like routing, controllers, and middleware support.</li><li><strong>Docker Containerization for Consistent Deployment : </strong>To ensure that the application runs consistently across different environments, Docker is used for containerization. This approach encapsulates the application with all its dependencies, facilitating seamless deployment and scalability.</li><li><strong>Swiss Ephemeris Integration for Precise Astronomical Calculations : </strong>The Swiss Ephemeris (swetest) is a high-precision ephemeris based on the DE431 by NASA’s JPL. Integrating it into the Jyotish API ensures accurate planetary positions, which are crucial for astrological computations.</li></ul><h4>Project Structure</h4><p>Understanding the organization of the project is crucial for developers who wish to contribute or integrate the Jyotish API into their applications. The project is structured to promote modularity, scalability, and ease of maintenance. The Jyotish API project consists of several key directories, each serving a specific purpose:</p><pre>jyotish-api/<br>├── api/<br>│   ├── config/<br>│   ├── public/<br>│   ├── src/<br>│   │   ├── Controller/APIController.php<br>│   │   ├── Service/<br>│   │   └── Kernel.php<br>│   ├── templates/<br>│   └── composer.json<br>├── lib/<br>│   ├── Alphabet/<br>│   ├── Bala/<br>│   ├── Bhava/<br>│   ├── Dasha/<br>│   ├── Ganita/<br>│   ├── Graha/<br>│   ├── Muhurta/<br>│   ├── Panchanga/<br>│   ├── Varga/<br>│   └── Yoga/<br>├── swetest/<br>│   └── src/<br>├── tests/<br>│   ├── unit/<br>│   │   ├── Bhava/<br>│   │   ├── Dasha/<br>│   │   ├── Graha/<br>│   │   └── Yoga/<br>│   └── phpunit.xml<br>├── docker-compose.yml<br>├── Dockerfile<br>└── README.md</pre><p>Kernel.php is the main kernel file that extends Symfony’s base kernel. It uses the MicroKernelTrait which provides a minimalistic kernel setup for Symfony applications. This is the core file that bootstraps the application.</p><p>APIController.php is the main API controller that handles all astrological calculations. It contains three main endpoints:</p><ul><li>ping: A health check endpoint that returns a simple pongresponse</li><li>calculate: Calculates astrological charts based on provided parameters (date, time, location)</li><li>getNowChart: Calculates astrological chart for the current moment</li></ul><p>The Jyotish API calulation library which is based on kunjara/jyotish library is organized into various modules, each responsible for specific astrological computations, this is located in api/lib/ :</p><pre>api/lib/<br>├── Alphabet/    # Sanskrit transliteration<br>├── Bala/        # Strength calculations<br>├── Bhava/       # House system implementations<br>├── Dasha/       # Planetary period calculations<br>├── Ganita/      # Mathematical computations<br>├── Graha/       # Planetary calculations<br>├── Muhurta/     # Electional astrology<br>├── Panchanga/   # Calendar elements<br>├── Varga/       # Divisional charts<br>├── Yoga/        # Planetary combinations<br>└── Lib.php      # Library callable functions</pre><p>Each directory corresponds to a fundamental aspect of Vedic astrology, encapsulating the logic and algorithms pertinent to that domain.</p><p>The Lib class in the Lib.phpfile serves as the main calculation engine for Vedic astrology within the application. Its primary functions include performing chart calculations, computing astrological data for the current moment, and managing timezone detection and adjustments. By handling these complex computations, the Lib class provides a clean and efficient interface for the API controller to interact with, abstracting the intricate details of astrological calculations.</p><p>One of the key methods in this class is calculator, which acts as the main entry point for chart calculations. This method accepts a variety of parameters that allow users to input precise data for accurate computations. These parameters include geographical location coordinates — latitude and longitude — to specify the exact position on Earth.</p><p>It also takes date components such as year, month, and day, as well as time components like hour, minute, and second, to define the exact moment for which the calculations are to be performed.</p><p>Additionally, the method accepts timezone and Daylight Saving Time (DST) settings to ensure that the time is correctly adjusted according to local standards. Users can specify Varga (divisional charts) settings to include various divisional charts in their calculations. Furthermore, the method allows for different levels of information detail through information level settings, catering to both basic and advanced astrological analysis.</p><p>Another significant method in the Libclass is calculateNow, designed to compute the astrological chart for the current moment. By default, this method sets the location to Tehran, Iran, using the coordinates 35.708309°N latitude and 51.380730°E longitude.</p><p>It automatically detects the appropriate timezone based on these coordinates, ensuring that the calculations reflect the correct local time. This method defaults to using the D1 and D9 divisional charts, which are fundamental in Vedic astrology for general life events and deeper insights into personal characteristics, respectively.</p><p>The getNearestTimezone method is crucial for accurate time-based calculations, as it determines the nearest timezone based on given geographical coordinates. It includes special handling for Iran by directly returning Asia/Tehranas the timezone identifier.</p><p>For other locations, the method utilizes spherical distance calculations to find the closest timezone, ensuring that users worldwide receive precise astrological data relevant to their local time. It returns both the timezone identifier and a formatted offset, which are essential for adjusting the calculations to the correct time zone.</p><p>The Libclass depends on several important Jyotish (Vedic astrology) calculation components to perform its functions effectively. It uses Base\Datafor core data structures and Base\Localityfor handling location-specific data.</p><p>For astronomical calculations, it relies on Ganita\Method\Swetest, which integrates with the Swiss Ephemeris — a high-precision ephemeris widely used in astrological software. The class employs Panchanga\AngaDifiner for Panchanga calculations, allowing for the determination of lunar days, yoga, karana, and other elements of the vedic calendar.</p><p>For calculating the ascendant (Lagna), it uses Graha\Lagna. Additionally, it incorporates various Bala calculators to assess the strength of planets, as well as yoga calculations to identify significant planetary combinations. Dasha calculations are also included to compute planetary periods, which are vital for predicting life events in Vedic astrology.</p><p>In terms of configuration, the Libclass includes a separate config.phpfile that contains essential configuration settings. It utilizes the Carbon library for advanced date and time handling, providing robust and flexible manipulation of date and time data. The class supports various calculation levels through the infolevelparameter, which allows users to specify the depth of information they require. The available levels include:</p><p>- Basic: Fundamental astrological calculations.<br>- A: Calculations related to a system of points that measure the strength of planets.<br>- Grahabala: Planetary strength calculations.<br>- Rashibala: Strength calculations of zodiac signs.<br>- Yogas: Determination of significant planetary combinations.<br>- Panchanga: Calculations related to the five limbs of the Panchanga.<br>- Transit: Analysis of planetary transits.</p><p>By supporting these levels, the Libclass provides flexibility for both novice users seeking basic astrological insights and advanced practitioners requiring detailed analyses.</p><h3>API Implementation Details</h3><p>Understanding the implementation of the API endpoints and their responses is crucial for effective integration.</p><h3>1. RESTful Endpoints</h3><p>`/api/calculate` : The primary endpoint for performing astrological calculations based on user-provided data such as date, time, and location.</p><p>Example of API call:</p><pre>http://localhost:9393/api/calculate?latitude=37.28077&amp;longitude=49.583057&amp;year=2023&amp;month=12&amp;day=25&amp;hour=12&amp;min=0&amp;sec=0&amp;time_zone=Asia/Tehran&amp;dst_hour=0&amp;dst_min=0&amp;nesting=0&amp;varga=D1,D9&amp;infolevel=basic,panchanga,transit</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHnnKFihZCbYi_w1h2iEvQ.png" /><figcaption>Query parameters</figcaption></figure><ul><li>Avaialable nesting for depth of Vimshottari dasha: 0, 1, 2, 3, 4</li><li>Available Vargas: D1, D2, D3, D4, D7, D9, D10, D12, D16, D20, D24, D27, D30, D40, D45, D60</li><li>Infolevel is a parameter to handle what response to have, basic , panchanga , ashtakavarga , grahabala , rashibala , yogas , transit</li></ul><p>Here is list of calculations:</p><ul><li><strong>Varga (Divisional) Charts</strong>: D1, D2, D3, D4, D7, D9, D10, D12, D16, D20, D24, D27, D30, D40, D45, D60</li><li><strong>Planetary Positions</strong>: Detailed positions of planets, Surya (Sun), Chandra (Moon), Mangal (Mars), Buddha (Mercury), Guru (Jupiter), Shukra (Venus), Shani (Staurn), Rahu and Ketu.</li><li><strong>Lagna</strong> (Ascendant) Calculations.</li><li><strong>Nakshatra</strong> Positions: Lunar mansions.</li><li><strong>Astangata</strong> (Combustion): Analysis of planets combust due to proximity to the Sun.</li><li><strong>Rashi Avastha</strong> (Planetary Dignity): Calculation of planetary dignity in different signs.</li><li><strong>Vargottama</strong>: Identification of planets occupying the same sign in both Rashi and Navamsa charts.</li><li>Planetary War (<strong>Yuddha</strong>): Detection of planetary wars when planets are within 1 degree of each other.</li></ul><h4>Panchanga Elements</h4><ul><li><strong>Tithi</strong>: Lunar day calculation.</li><li><strong>Nakshatra</strong>: Determination of the current lunar mansion.</li><li><strong>Yoga</strong>: Calculation of the Yoga formed by the positions of the Sun and Moon.</li><li><strong>Karana</strong>: Half of a Tithi, used in muhurta (electional astrology).</li><li><strong>Vara</strong>: Day of the week.</li></ul><h4>Strength Calculations</h4><ul><li><strong>Ashtakavarga</strong>: Point-based system to analyze planetary strengths.</li><li><strong>Graha Bala </strong>(Planetary Strength): Comprehensive strength analysis of planets.</li><li><strong>Rashi Bala </strong>(Sign Strength): Strength of the zodiac signs.</li></ul><h4>Yoga Calculations</h4><ul><li><strong>Dhana Yoga:</strong> Wealth-producing combinations.</li><li><strong>Mahapurusha</strong> <strong>Yoga</strong>: Great person yogas formed by certain planetary positions.</li><li><strong>Nabhasha</strong> <strong>Yoga</strong>: Yogas based on planetary patterns.</li><li><strong>Parivarthana</strong> <strong>Yoga</strong>: Mutual exchange of signs between planets.</li><li><strong>Raja</strong> <strong>Yoga</strong>: Combinations indicating power and authority.</li><li><strong>Sannyasa</strong> <strong>Yoga</strong>: Combinations indicating renunciation.</li></ul><h4>Additional Features</h4><ul><li>Dasha Calculations (Vimshottari): Planetary periods analysis.</li><li>Supported Ayanamshas: Deluce , Djwhalkhul , Fagan , Jnbhasin , Krishnamurti , Lahiri , Raman , Sassanian , Ushashashi , Yukteshwar</li></ul><p>Another route is`/api/now` , which generates astrological data for the current moment, useful for applications requiring real-time calculations. This routes accepts latitude and longitude and timezone will automatically set base on location.</p><h3>2. Response Structure</h3><ul><li><strong>Hierarchical JSON Response Format</strong> : The API returns data in a structured JSON format, facilitating easy parsing and integration into applications. The hierarchical structure ensures that related data is grouped logically.</li><li><strong>Comprehensive Error Handling</strong> : Errors are communicated through standardized HTTP status codes and detailed messages within the JSON response, aiding developers in debugging and providing user feedback.</li><li><strong>Performance Optimization for Large Calculations</strong> : The API is optimized to handle extensive calculations efficiently, ensuring that performance remains robust even when processing complex astrological computations.</li></ul><pre>{<br>  &quot;chart&quot;: {<br>    &quot;user&quot;: {<br>      &quot;datetime&quot;: &quot;2023-12-25 12:00:00&quot;,<br>      &quot;timezone&quot;: &quot;+03:30&quot;,<br>      &quot;longitude&quot;: 49.583057,<br>      &quot;latitude&quot;: 37.28077,<br>      &quot;altitude&quot;: 0<br>    },<br>    &quot;graha&quot;: {<br>      &quot;Sy&quot;: {<br>        &quot;longitude&quot;: 248.983163,<br>        &quot;latitude&quot;: 0.0001772,<br>        &quot;speed&quot;: 1.0183709,<br>        &quot;ascension&quot;: 273.4600331,<br>        &quot;declination&quot;: -23.3978588,<br>        &quot;rashi&quot;: 9,<br>        &quot;degree&quot;: 8.98316299999999,<br>        &quot;nakshatra&quot;: {<br>          &quot;anga&quot;: &quot;nakshatra&quot;,<br>          &quot;key&quot;: 19,<br>          &quot;ratio&quot;: 1,<br>          &quot;abhijit&quot;: false,<br>          &quot;left&quot;: 32.62627750000016,<br>          &quot;name&quot;: &quot;Moola&quot;,<br>          &quot;pada&quot;: 3<br>        },<br>        &quot;astangata&quot;: null,<br>        &quot;rashiAvastha&quot;: &quot;friend&quot;,<br>        &quot;vargottama&quot;: false,<br>        &quot;yuddha&quot;: null,<br>        &quot;gocharastha&quot;: 0,<br>        &quot;bhavaCharacter&quot;: &quot;mishra&quot;,<br>        &quot;tempRelation&quot;: {<br>          &quot;Ch&quot;: -1,<br>          &quot;Ma&quot;: 1,<br>          &quot;Bu&quot;: -1,<br>          &quot;Gu&quot;: -1,<br>          &quot;Sk&quot;: 1,<br>          &quot;Sa&quot;: 1,<br>          &quot;Ra&quot;: 1,<br>          &quot;Ke&quot;: 1<br>        },<br>        &quot;relation&quot;: {<br>          &quot;Ch&quot;: 0,<br>          &quot;Ma&quot;: 2,<br>          &quot;Bu&quot;: -1,<br>          &quot;Gu&quot;: 0,<br>          &quot;Sk&quot;: 0,<br>          &quot;Sa&quot;: 0,<br>          &quot;Ra&quot;: 0,<br>          &quot;Ke&quot;: 0,<br>          &quot;Sy&quot;: null<br>        },<br>        &quot;yogakaraka&quot;: false,<br>        &quot;mrityu&quot;: false,<br>        &quot;pushkaraNavamsha&quot;: false,<br>        &quot;pushkaraBhaga&quot;: false,<br>        &quot;avastha&quot;: {<br>          &quot;baladi&quot;: &quot;kumara&quot;,<br>          &quot;jagradi&quot;: &quot;swapna&quot;,<br>          &quot;deeptadi&quot;: [<br>            &quot;shanta&quot;<br>          ]<br>        },<br>        &quot;dispositor&quot;: &quot;Gu&quot;<br>      },<br>      &quot;Ch&quot;: {},<br>      &quot;Ma&quot;: {},<br>      &quot;Bu&quot;: {},<br>      &quot;Gu&quot;: {},<br>      &quot;Sk&quot;: {},<br>      &quot;Sa&quot;: {},<br>      &quot;Ra&quot;: {},<br>      &quot;Ke&quot;: {},<br>    },<br>    &quot;bhava&quot;: {<br>      &quot;1&quot;: {<br>        &quot;longitude&quot;: 327.9252867,<br>        &quot;ascension&quot;: 330.1017467,<br>        &quot;declination&quot;: -12.1928517,<br>        &quot;rashi&quot;: 11,<br>        &quot;degree&quot;: 27.925286700000015<br>      },<br>      &quot;2&quot;: {},<br>      &quot;3&quot;: {},<br>      &quot;4&quot;: {},<br>      &quot;5&quot;: {},<br>      &quot;6&quot;: {},<br>      &quot;7&quot;: {},<br>      &quot;8&quot;: {},<br>      &quot;9&quot;: {},<br>      &quot;10&quot;: {},<br>      &quot;11&quot;: {},<br>      &quot;12&quot;: {},<br>    },<br>    &quot;lagna&quot;: {<br>      &quot;Lg&quot;: {<br>        &quot;longitude&quot;: 327.9252867,<br>        &quot;ascension&quot;: 330.1017467,<br>        &quot;declination&quot;: -12.1928517,<br>        &quot;rashi&quot;: 11,<br>        &quot;degree&quot;: 27.925286700000015,<br>        &quot;nakshatra&quot;: {<br>          &quot;anga&quot;: &quot;nakshatra&quot;,<br>          &quot;key&quot;: 25,<br>          &quot;ratio&quot;: 1,<br>          &quot;abhijit&quot;: false,<br>          &quot;left&quot;: 40.56034975,<br>          &quot;name&quot;: &quot;Purva Bhadrapada&quot;,<br>          &quot;pada&quot;: 3<br>        }<br>      },<br>      &quot;MLg&quot;: {<br>        &quot;longitude&quot;: 240.7308939,<br>        &quot;ascension&quot;: 238.5809717,<br>        &quot;declination&quot;: -20.3009012,<br>        &quot;rashi&quot;: 9,<br>        &quot;degree&quot;: 0.7308939000000123<br>      }<br>    },<br>    &quot;varga&quot;: {<br>      &quot;D9&quot;: {<br>        &quot;bhava&quot;: {<br>          &quot;1&quot;: {<br>            &quot;rashi&quot;: 3,<br>            &quot;degree&quot;: 11.327580300000125,<br>            &quot;longitude&quot;: 71.32758030000012<br>          },<br>          &quot;2&quot;: {},<br>          &quot;3&quot;: {},<br>          &quot;4&quot;: {},<br>          &quot;5&quot;: {},<br>          &quot;6&quot;: {},<br>          &quot;7&quot;: {},<br>          &quot;8&quot;: {},<br>          &quot;9&quot;: {},<br>          &quot;10&quot;: {},<br>          &quot;11&quot;: {},<br>          &quot;12&quot;: {},<br>        },<br>        &quot;graha&quot;: {<br>          &quot;Sy&quot;: {<br>            &quot;rashi&quot;: 3,<br>            &quot;degree&quot;: 20.84846699999991,<br>            &quot;speed&quot;: 1.0183709,<br>            &quot;longitude&quot;: 80.84846699999991<br>          },<br>          &quot;Ch&quot;: {},<br>          &quot;Ma&quot;: {},<br>          &quot;Bu&quot;: {},<br>          &quot;Gu&quot;: {},<br>          &quot;Sk&quot;: {},<br>          &quot;Sa&quot;: {},<br>          &quot;Ra&quot;: {},<br>          &quot;Ke&quot;: {},<br>        },<br>        &quot;lagna&quot;: {<br>          &quot;Lg&quot;: {<br>            &quot;rashi&quot;: 3,<br>            &quot;degree&quot;: 11.327580300000125,<br>            &quot;longitude&quot;: 71.32758030000012<br>          },<br>          &quot;MLg&quot;: {<br>            &quot;rashi&quot;: 1,<br>            &quot;degree&quot;: 6.578045100000111,<br>            &quot;longitude&quot;: 6.578045100000111<br>          }<br>        }<br>      }<br>    },<br>    &quot;panchanga&quot;: {<br>      &quot;tithi&quot;: {<br>        &quot;anga&quot;: &quot;tithi&quot;,<br>        &quot;key&quot;: 14,<br>        &quot;name&quot;: &quot;Chaturdashi&quot;,<br>        &quot;paksha&quot;: &quot;shukla&quot;,<br>        &quot;left&quot;: 75.43356083333303<br>      },<br>      &quot;nakshatra&quot;: {<br>        &quot;anga&quot;: &quot;nakshatra&quot;,<br>        &quot;key&quot;: 4,<br>        &quot;ratio&quot;: 1,<br>        &quot;abhijit&quot;: false,<br>        &quot;left&quot;: 40.51648225000003,<br>        &quot;name&quot;: &quot;Rohini&quot;,<br>        &quot;pada&quot;: 3<br>      },<br>      &quot;yoga&quot;: {<br>        &quot;anga&quot;: &quot;yoga&quot;,<br>        &quot;key&quot;: 23,<br>        &quot;name&quot;: &quot;Shubha&quot;,<br>        &quot;left&quot;: 73.14275974999997<br>      },<br>      &quot;vara&quot;: {<br>        &quot;anga&quot;: &quot;vara&quot;,<br>        &quot;left&quot;: 81.29129302863754,<br>        &quot;key&quot;: &quot;Ch&quot;,<br>        &quot;week&quot;: &quot;1&quot;,<br>        &quot;name&quot;: &quot;Somavar&quot;<br>      },<br>      &quot;karana&quot;: {<br>        &quot;anga&quot;: &quot;karana&quot;,<br>        &quot;key&quot;: 5,<br>        &quot;name&quot;: &quot;Gara&quot;,<br>        &quot;left&quot;: 50.867121666666065<br>      }<br>    },<br>    &quot;rising&quot;: {<br>      &quot;Sy&quot;: [<br>        {<br>          &quot;rising&quot;: &quot;2023-12-24 07:30:04&quot;,<br>          &quot;setting&quot;: &quot;2023-12-24 17:40:54&quot;<br>        },<br>        {<br>          &quot;rising&quot;: &quot;2023-12-25 07:30:31&quot;,<br>          &quot;setting&quot;: &quot;2023-12-25 17:41:27&quot;<br>        },<br>        {<br>          &quot;rising&quot;: &quot;2023-12-26 07:30:56&quot;,<br>          &quot;setting&quot;: &quot;2023-12-26 17:42:02&quot;<br>        }<br>      ]<br>    },<br>    &quot;kala&quot;: {<br>      &quot;hora&quot;: {<br>        &quot;number&quot;: 7,<br>        &quot;key&quot;: &quot;Bu&quot;,<br>        &quot;interval&quot;: 3054.6666666666665,<br>        &quot;left&quot;: 47.173723264949835,<br>        &quot;type&quot;: &quot;yama&quot;,<br>        &quot;end&quot;: &quot;2023-12-25 13:26:54&quot;<br>      }<br>    },<br>    &quot;dasha&quot;: {<br>      &quot;nesting&quot;: 0,<br>      &quot;type&quot;: &quot;vimshottari&quot;,<br>      &quot;key&quot;: &quot;&quot;,<br>      &quot;duration&quot;: 3786834240,<br>      &quot;start&quot;: &quot;2018-01-12 22:49:09&quot;,<br>      &quot;end&quot;: &quot;2138-01-13 01:13:09&quot;,<br>      &quot;periods&quot;: {<br>        &quot;Ch&quot;: {<br>          &quot;nesting&quot;: 1,<br>          &quot;type&quot;: &quot;mahadasha&quot;,<br>          &quot;key&quot;: &quot;Ch&quot;,<br>          &quot;duration&quot;: 315569520,<br>          &quot;start&quot;: &quot;2018-01-12 22:49:09&quot;,<br>          &quot;end&quot;: &quot;2028-01-13 09:01:09&quot;<br>        },<br>        &quot;Ma&quot;: {},<br>        &quot;Ra&quot;: {},<br>        &quot;Gu&quot;: {},<br>        &quot;Sa&quot;: {},<br>        &quot;Bu&quot;: {},<br>        &quot;Ke&quot;: {},,<br>        &quot;Sk&quot;: {},,<br>        &quot;Sy&quot;: {},<br>      }<br>    }<br>  },<br>  &quot;duration_of_response&quot;: 0.12,<br>  &quot;created_at&quot;: &quot;2025-02-08 23:55:46&quot;<br>}</pre><h3>Swiss Ephemeris Integration</h3><ul><li><strong>Compilation and Integration Process : </strong>The swetest tool from the Swiss Ephemeris is compiled within the Docker container. This process is essential for integrating the ephemeris into the API environment.</li><li><strong>Error Handling and Fallback Mechanisms : </strong>The API includes mechanisms to handle any compilation or runtime errors related to the ephemeris, ensuring that the service remains operational and providing fallback options if needed.</li></ul><h3>GNU Free Software and Open Source Philosophy</h3><p>The Jyotish API is built on the foundation of GNU Free Software , embracing the principles of open-source development. By leveraging the kunjara/jyotishlibrary, which is licensed under the GNU General Public License (GPL) , the API ensures transparency, accessibility, and community-driven innovation. This alignment with free software principles allows developers to:</p><ol><li><strong>Access and Modify Source Code</strong> : The API’s source code is open for inspection and modification, encouraging collaboration and continuous improvement.</li><li><strong>Promote Knowledge Sharing </strong>: By making the API freely available, it fosters a culture of sharing knowledge and tools within the astrological community.</li><li><strong>Ensure Data Integrity</strong> : The use of open-source libraries like Swiss Ephemeris guarantees that astronomical calculations are accurate and free from proprietary constraints.</li></ol><p>I’ve found this approach is intentionally structured to reflect the essence of the Kali Yuga — an era marked by the democratization of knowledge, where individuals are increasingly equipped to unravel the intricate mysteries of cosmic existence.</p><h4>Last word</h4><p>My experience and knowledge in programming, along with learning Ayurvedic Astrology from Dr. David Frawley, led me to realize the importance of sharing knowledge openly.</p><p>Therefore, I decided to offer my project as open source so that everyone, wherever they are, can have access to these valuable calculations. In today’s world, knowledge and information should not be limited to a select group, and I believe that only through free sharing and exchange can we achieve true development and progress.</p><p>I hope for a day when everyone embraces this belief and together, we contribute to the expansion of global knowledge.</p><p>Long live shared knowledge and collective advancement!</p><p>Repository: <a href="https://github.com/teal33t/jyotish-api">https://github.com/teal33t/jyotish-api</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1795e7437555" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SQLite: An In-Depth Exploration with Richard Hipp]]></title>
            <link>https://medium.com/@teal33t/understanding-sqlite-an-in-depth-exploration-with-richard-hipp-5b2e9b1d012e?source=rss-7f2339b3b56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b2e9b1d012e</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Saman Esmaeil]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 11:47:17 GMT</pubDate>
            <atom:updated>2025-01-26T11:47:17.499Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZSKLA81tBis%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZSKLA81tBis&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZSKLA81tBis%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc7ef4f1d367e648cd77407190f87c41/href">https://medium.com/media/fc7ef4f1d367e648cd77407190f87c41/href</a></iframe><p>SQLite is often described as the most widely deployed database engine in the world. Embedded in billions of devices and applications, it quietly powers everything from smartphones and web browsers to aerospace technology and financial systems. But what makes SQLite so ubiquitous, and how does it work under the hood?</p><p>In a recent conference talk, Dr. Richard Hipp, the inventor and lead developer of SQLite, delved into the intricacies of this lightweight yet powerful database engine. This article provides a comprehensive overview of the key points from his talk, exploring SQLite’s distinctive features, internal architecture, and the philosophy that guides its development.</p><h3>Introduction</h3><p>Dr. Richard Hipp’s journey with SQLite began not out of a desire to become a database expert, but from a practical need to simplify application development. Holding a Ph.D. in computational linguistics rather than database technology, Hipp found himself frustrated with the complexities and dependencies of client-server databases in the early 2000s. This led him to create SQLite — a self-contained, serverless, zero-configuration, transactional SQL database engine.</p><p>Fast forward to today, SQLite has become an integral part of countless applications and devices. Its design philosophy emphasizes simplicity and reliability, striving to solve more problems than it creates. As Hipp puts it, “Your enemy is complexity,” and SQLite aims to reduce that complexity wherever possible.</p><h3>Distinctive Features of SQLite</h3><p>SQLite stands out from other database engines due to several distinctive features that make it ideal for a wide range of applications, particularly those embedded in devices or requiring minimal overhead.</p><h3>Serverless Architecture</h3><p>Unlike traditional client-server database systems (such as MySQL, PostgreSQL, or Oracle), SQLite operates as an embedded database engine. There is no separate server process; instead, the database engine runs within the same process space as the application. This eliminates the need for inter-process communication and reduces the risk of the application failing due to server unavailability.</p><h3>Single File Database</h3><p>All of the data in an SQLite database is stored in a single, cross-platform disk file. This file can include multiple tables, indexes, views, and triggers. The single-file format simplifies management, backup, and data exchange. It also allows the database file to serve as an application file format, which can be easily shared via email or other file-transfer methods.</p><h3>Zero Configuration and Public Domain Licensing</h3><p>SQLite requires no configuration or administration. There are no setup procedures, and it doesn’t require a dedicated database administrator. Moreover, SQLite’s source code is in the public domain, meaning it can be used for any purpose (commercial or personal) without paying licensing fees or worrying about legal restrictions.</p><h3>Lightweight and Efficient</h3><p>Despite its small size (the source code can be compiled into a binary less than 600KB in size), SQLite is a fully featured SQL database engine. It supports transactions, subqueries, triggers, views, and complex SQL functions. It’s optimized for embedded devices and applications, providing fast and efficient data manipulation.</p><h3>High Reliability and Long-term Support</h3><p>SQLite is known for its reliability and robustness. It’s recommended by organizations like the U.S. Library of Congress for long-term data storage. The developers have committed to maintaining database file format stability through the year 2050, ensuring that databases created today will remain accessible for decades.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zr1V0NKdv7rtEHpI.png" /></figure><h3>When to Use SQLite</h3><p>SQLite is ideal for applications where simplicity, reliability, and minimal overhead are paramount. Some common scenarios include:</p><ul><li>Embedded Devices: Smartphones, IoT devices, and consumer electronics where resources are limited.</li><li>Local Storage: Applications that require a lightweight database for storing user preferences, configurations, or caching.</li><li>Application File Format: Replacing custom file formats with a database file to leverage SQL’s querying capabilities.</li><li>Testing and Prototyping: Rapid development without the need for database server setup.</li></ul><p>However, SQLite may not be suitable for scenarios requiring:</p><ul><li>Client-Server Architecture: When the database must be accessed over a network by multiple clients simultaneously.</li><li>High Concurrency with Concurrent Writers: Systems requiring multiple simultaneous writes from different processes.</li><li>Big Data Applications: Databases larger than the practical limits of SQLite (up to 281 terabytes, though hardware limitations usually apply).</li></ul><h3>Internal Implementation of SQLite</h3><p>Understanding how SQLite works internally provides insights into its performance characteristics and limitations. The architecture is designed to be simple yet powerful, allowing it to run efficiently even on devices with limited resources.</p><h3>High-Level Architecture</h3><p>SQLite’s architecture can be broken down into several key components:</p><ol><li>Interface Layer: Provides the Application Programming Interface (API) that applications use to interact with the database engine.</li><li>Compiler (Parser and Code Generator): Parses SQL statements and generates bytecode instructions for the virtual machine.</li><li>Virtual Machine: Executes the bytecode instructions generated by the compiler.</li><li>Storage Engine (B-Tree and Pager): Manages the storage and retrieval of data on disk.</li><li>Operating System Interface: Abstracts the underlying file system operations to maintain portability across platforms.</li></ol><h3>Application Programming Interface</h3><p>SQLite’s API is designed to be straightforward and easy to use. The core concepts revolve around two primary objects:</p><ul><li>Database Connection (`sqlite3` object): Represents an open connection to a database file.</li><li>Prepared Statement (`sqlite3_stmt` object): Represents a compiled SQL statement ready for execution.</li></ul><p>The typical workflow involves:</p><ol><li>Opening a Connection: Using `sqlite3_open()` to connect to a database file.</li><li>Preparing a Statement: Using `sqlite3_prepare_v2()` to compile an SQL query into bytecode.</li><li>Executing the Statement: Using functions like `sqlite3_step()` to execute the prepared statement and retrieve results.</li><li>Finalizing the Statement: Using `sqlite3_finalize()` to clean up resources.</li><li>Closing the Connection: Using `sqlite3_close()` when done with the database.</li></ol><h3>Compiler: Parser and Code Generator</h3><p>The compiler’s role is to convert SQL statements into bytecode that the virtual machine can execute. The process involves:</p><ul><li>Parsing: Tokenizing the SQL text and building an Abstract Syntax Tree (AST).</li><li>Semantic Analysis: Resolving table and column names, data types, and checking for errors.</li><li>Optimization: Rewriting queries for efficiency, such as flattening subqueries, pushing down predicates, and simplifying expressions.</li><li>Code Generation: Translating the optimized AST into a sequence of bytecode instructions.</li></ul><h3>Virtual Machine and Bytecode</h3><p>SQLite’s Virtual Machine (VM) is a stack-based interpreter that executes the bytecode generated by the compiler. The bytecode instructions are higher-level compared to typical machine code, including operations specific to database manipulation, such as:</p><ul><li>Cursor Operations: Open, close, and navigate cursors on tables and indexes.</li><li>Data Retrieval and Storage: Read and write values to and from tables.</li><li>Control Flow: Branching, looping, and subroutine calls.</li><li>Expression Evaluation: Performing arithmetic and logical operations.</li></ul><p>Developers can view the bytecode for a query by prefixing it with the `EXPLAIN` keyword, which is useful for understanding query execution and debugging.</p><h3>Storage Engine: B-Tree and Pager Layers</h3><p>The storage engine is responsible for organizing data on disk in a way that supports efficient retrieval and modification.</p><h4>B-Tree Layer</h4><p>SQLite uses B-Trees (and B+ Trees) to store both tables and indexes:</p><ul><li>Tables as B-Trees: Each table is a B-Tree where the keys are row IDs, and the values are the row data.</li><li>Indexes as B-Trees: Indexes are B-Trees where the keys are the indexed column values, and the values are the row IDs.</li></ul><p>This structure allows for efficient range queries, insertions, and deletions.</p><h4>Pager Layer</h4><p>The pager layer manages the reading and writing of database pages to and from disk. It provides:</p><ul><li>Caching: Pages are cached in memory for performance.</li><li>Atomic Commit and Rollback: Ensures that transactions are atomic, consistent, isolated, and durable (ACID properties).</li><li>Concurrency Control: Manages locks to prevent conflicts between concurrent readers and writers.</li></ul><h3>Operating System Interface</h3><p>SQLite abstracts file system interactions through an OS interface layer, making it portable across different operating systems like Unix, Windows, and others. This layer handles:</p><ul><li>File Access: Opening, reading, writing, and closing files.</li><li>Locking Mechanisms: Implementing file locks for concurrency control.</li><li>Shared Memory Management: Used in certain journal modes to coordinate multiple processes.</li></ul><h3>Transaction Management</h3><p>SQLite ensures data integrity through robust transaction management mechanisms, primarily using rollback journals and write-ahead logs.</p><h3>Rollback Journal</h3><p>The default method for transaction management in SQLite is the rollback journal:</p><ol><li>Begin Transaction: A reserved lock is taken on the database file.</li><li>Save Original Pages: Pages that will be modified are copied into the rollback journal before changes are made.</li><li>Modify Data: Changes are made to the pages in memory.</li><li>Commit Transaction: The modified pages are written to disk, and the rollback journal is deleted atomically.</li><li>Recovery: If a crash occurs before the transaction commits, the rollback journal is used to restore the database to its original state upon the next connection.</li></ol><h3>Write-Ahead Log (WAL)</h3><p>An alternative mode is the write-ahead log, which can offer better performance and concurrency:</p><ol><li>Write Changes to WAL: Modifications are appended to a separate WAL file without modifying the database file directly.</li><li>Readers and Writers Concurrency: Readers can continue accessing the unmodified database while writers append to the WAL.</li><li>Checkpointing: Periodically, changes in the WAL are merged back into the main database file.</li><li>Recovery: In case of a crash, the WAL is used to bring the database to a consistent state upon the next connection.</li></ol><p>The WAL mode allows for higher concurrency since readers are not blocked by writers and vice versa.</p><h3>Data Storage and Formats</h3><p>SQLite uses a flexible storage format that allows for efficient storage and retrieval of data.</p><h3>Variable-Length Data Types</h3><p>SQLite’s data types are dynamic, and the storage format supports variable-length integers and other data types to save space. This flexibility means that columns can store different types of data without rigid type enforcement.</p><h3>Tuple Format</h3><p>Rows in SQLite tables are stored as serialized byte streams, consisting of:</p><ul><li>Header: Contains the number of columns and metadata about data types.</li><li>Payload: The actual data values.</li></ul><p>This self-contained format allows SQLite to read and write rows efficiently without needing external schema information.</p><h3>Query Planning and Optimization</h3><p>SQLite’s query planner transforms SQL queries into efficient execution plans using cost-based optimization.</p><h3>Cost Estimation</h3><p>The planner estimates the cost of different query plans based on factors like:</p><ul><li>Table and Index Statistics: Information about the size of tables and the selectivity of indexes.</li><li>Operation Costs: Estimated computational costs for operations like table scans, index lookups, and joins.</li></ul><h3>Join Ordering</h3><p>For queries involving joins, SQLite evaluates different join orders to find the most efficient sequence. It uses heuristics and cost estimates to prevent the combinatorial explosion of possible join permutations.</p><h3>Index Selection</h3><p>The planner decides whether to use indexes based on their availability and estimated benefit. It can choose between full table scans, index scans, and other access methods.</p><h3>Query Flattening and Subquery Optimization</h3><p>SQLite performs transformations like:</p><ul><li>Flattening Subqueries: Integrating subqueries into the main query to avoid nested loops.</li><li>Predicate Pushdown: Moving filter conditions closer to the data source to reduce the amount of data processed.</li></ul><h3>Execution Plan Visualization</h3><p>Tools like the `EXPLAIN QUERY PLAN` command allow developers to see the query planner&#39;s decisions, helping with optimization and debugging.</p><h3>Testing and Reliability</h3><p>SQLite is renowned for its thorough testing and reliability. The development team employs meticulous testing methodologies, including:</p><ul><li>100% Branch Test Coverage: Every possible branch in the code is tested to ensure correctness.</li><li>Fuzz Testing: Randomized inputs are used to detect unexpected behavior or vulnerabilities.</li><li>Durability Testing: Simulating power failures and crashes to verify that the database recovers gracefully.</li></ul><p>These practices contribute to SQLite’s reputation as one of the most reliable software systems in use.</p><h3>Community and Development Philosophy</h3><p>While SQLite is open-source and public domain, the development team maintains tight control over the core codebase to ensure consistency and quality:</p><ul><li>Small Core Team: A handful of trusted developers contribute to the core, minimizing the risk of introducing bugs.</li><li>Public Domain License: Allows unrestricted use, modification, and distribution.</li><li>Longevity Commitment: The developers have pledged to maintain backward compatibility and support the database format for decades.</li></ul><h3>Conclusion</h3><p>SQLite’s success lies in its unique combination of simplicity, reliability, and powerful features. By embedding the database engine directly into applications and adhering to a design philosophy that values minimalism and practicality, SQLite solves many problems associated with traditional database systems.</p><p>Dr. Richard Hipp’s insights highlight the thoughtful engineering and considerations that have gone into SQLite’s development. From its serverless architecture and single-file database format to its internal mechanisms for ensuring data integrity and performance, SQLite serves as a remarkable example of efficient software design.</p><p>Whether you’re developing a mobile app, working with embedded systems, or need a lightweight database solution, SQLite offers a compelling option that is both accessible and robust.</p><h3>Questions and Answers Highlights</h3><p>During the conference talk, several interesting questions were raised by the audience, providing further insights into SQLite’s use cases and development.</p><h3>Bus Factor and Development Team</h3><p>Question: With such a small core team, what happens if key developers are unavailable?</p><p>Answer: Dr. Hipp acknowledged the concern, often referred to as the “bus factor.” To mitigate this, the SQLite Consortium was established, supported by various companies. Although the development team remains small to maintain quality and consistency, the open-source nature of SQLite allows others to step in if necessary.</p><h3>Extensions and Language Support</h3><p>Question: Does the SQLite team maintain extensions for various programming languages?</p><p>Answer: The core team focuses primarily on maintaining SQLite itself and provides extensions for Tcl and Java (through JNI). Extensions for other languages, like Python, are maintained by the community. While the team offers support and makes it easy for extension writers, they do not maintain these extensions directly.</p><h3>Type System and Flexibility</h3><p>Question: How does SQLite handle data types, and does the dynamic typing lead to issues?</p><p>Answer: SQLite’s flexible typing is by design, allowing for dynamic data storage without rigid type enforcement. This can lead to conflicts when porting applications to databases with strict typing, like PostgreSQL or MySQL, but within SQLite, it offers flexibility without significant issues.</p><h3>Security Considerations</h3><p>Question: Is it safe to allow users to run arbitrary queries on an SQLite database?</p><p>Answer: SQLite is designed to handle arbitrary SQL inputs securely, even with malformed queries or database files. Extensive testing ensures that these inputs do not cause memory errors or crashes. However, allowing access to the C API or arbitrary bytecode execution is not safe, as it would bypass these protections.</p><h3>Additional Resources</h3><p>For those interested in exploring SQLite further:</p><ul><li>SQLite Official Website: <a href="https://www.sqlite.org/">www.sqlite.org</a></li><li>SQLite Documentation: Comprehensive guides and API references.</li><li>SQLite Source Code: Available in the public domain for study and modification.</li><li>SQLite Forum: A place to ask questions and engage with the community.</li><li>SQLite Fiddle: An online tool to experiment with SQLite queries (<a href="https://sqlite.org/fiddle">SQLite Fiddle</a>).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b2e9b1d012e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking Down PASETO vs. JWT: Which Token is Right for You?]]></title>
            <link>https://systemweakness.com/breaking-down-paseto-vs-jwt-which-token-is-right-for-you-f084ed952586?source=rss-7f2339b3b56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f084ed952586</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[paseto]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Saman Esmaeil]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 11:47:44 GMT</pubDate>
            <atom:updated>2025-02-25T10:46:15.835Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Best Security Token? A Deep Dive into PASETO vs. JWT</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-zDAzAc7QUsWQo8f" /></figure><p>In the world of web and mobile application development, security is paramount. Authentication mechanisms are critical in ensuring that user data remains secure and that interactions are authenticated properly before access is granted. Token-based authentication has become a popular approach due to its scalability and ease of use. While JSON Web Tokens (JWT) have been the standard for a long time, Platform-Agnostic Security Tokens (PASETO) have emerged as a robust alternative, offering solutions to many of JWT’s inherent issues. In this article, we dive deep into the world of token-based authentication, comparing JWT and PASETO, and exploring why PASETO might be a better choice for your security needs.</p><h3>What is Authentication?</h3><p>Authentication is a security process that verifies the identity of a user or device attempting to access a system. The goal of authentication is to ensure that users are who they claim to be. This process is crucial in controlling access to resources and in maintaining the security of an application or system.</p><p>Effective authentication mechanisms prevent unauthorized access, ensuring that only legitimate users can perform actions within the system.</p><p>Token-based authentication is a security mechanism where, upon successfully logging in with a username and password, a server issues a token. This token is then used by the client for subsequent requests to access secured resources.</p><h3>What is JSON Web Tokens (JWT) ?</h3><p><a href="https://www.rfc-editor.org/rfc/rfc7519">JSON Web Tokens</a> offer a compact and self-contained way for securely transmitting information between parties as a JSON object, and they can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.</p><p>Here’s a step-by-step breakdown of how it works:</p><ol><li><strong>User Provides Credentials: </strong>The process begins when a user enters their credentials (such as a username and password) into a client application (e.g., a web or mobile app).</li><li><strong>Client Requests Token: </strong>The client sends these credentials to the server. This request for a token includes the user’s credentials, which are necessary for authentication.</li><li><strong>Server Verifies Credentials: </strong>Upon receiving the credentials, the server interacts with its database to verify the user’s credentials. This involves checking if the provided username and password match the records stored in the database.</li><li><strong>Database Returns User Data: </strong>If the credentials are correct, the database sends back user data to the server. This data typically includes information that will be used to create the JWT, such as the user’s identity and any roles or permissions.</li><li><strong>Server Issues Token: </strong>The server then creates a JWT, incorporating the user data. The token is encoded and signed, ensuring that it cannot be tampered with without detecting the modification. This token is then sent back to the client.</li><li><strong>Client Receives Token: </strong>The client receives the JWT and typically stores it, often in local storage or a cookie, to maintain the user’s session.</li><li><strong>User Requests Protected Resource: </strong>When the user wants to access a protected resource (like a profile page or confidential data), the client sends a new request to the server. This request includes the JWT as a part of the authorization header.</li><li><strong>Server Validates Token: </strong>The server receives the request and first validates the JWT. This validation involves checking the token’s integrity and authenticity, usually by verifying the signature with a secret key or a public/private key pair, depending on the signing method used.</li><li><strong>Access to Protected Resource: </strong>If the token is valid, the server grants access to the requested resource. The server sends the protected resource back to the client.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*NoDa6r9MV6YXKUVU" /><figcaption>The following sequence describes how a JSON Web Token (JWT) is typically used in client-server communication for authentication and authorization purposes.</figcaption></figure><p>The lifecycle of token-based authentication ensures that users do not need to re-submit their credentials every time they access a new resource, thereby enhancing both security and convenience. Also here are the main components of a JWT:</p><ol><li><strong>Header</strong>: The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HS256.</li><li><strong>Payload</strong>: The payload contains the claims. These claims could be the user ID, an expiration time (exp), issuer (iss), subject (sub), and others.</li><li><strong>Signature</strong>: To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.</li><li><strong>Compact Structure</strong>: The resultant JWT appears as three Base64-URL strings separated by dots that can be easily passed in HTML and HTTP environments.</li></ol><h3>Security Considerations for JWT</h3><p>A critical issue in JWT is the inclusion of the signing algorithm in the token’s header. This seemingly harmless feature can, unfortunately, be exploited in several ways:</p><ol><li><strong>Algorithm “None” Attack</strong>: In some cases, attackers can manipulate the alg header field to none, effectively bypassing the signature verification process. This vulnerability arises because the token explicitly tells the server how to verify its signature, and by setting it to none, the server may skip verification altogether if not properly configured to reject such tokens.</li><li><strong>Symmetric vs. Asymmetric Key Confusion</strong>: A more sophisticated attack involves changing the alg header from an asymmetric algorithm (like RSA) to a symmetric one (like HS256). Here&#39;s how this attack unfolds:</li></ol><ul><li>The attacker knows the server uses RSA (RS256) for signing tokens.</li><li>They craft a new token and set the alg to HS256, a symmetric algorithm.</li><li>Using the public RSA key (which is not designed as a secret key), the attacker signs the token.</li><li>The server, misled by the alg header to use HS256, attempts to verify the token using the RSA public key as if it were a symmetric secret key.</li><li>Because the same key is used to both sign and verify the signature in HS256, the verification erroneously succeeds, granting the attacker access.</li></ul><p>To mitigate these risks, developers must implement robust checks:</p><ul><li><strong>Validate Algorithm Header</strong>: Always ensure that the alg header in the token matches the expected algorithm used by the server. This validation should be non-negotiable and coded explicitly in the server logic.</li><li><strong>Use Libraries Wisely</strong>: Choose well-maintained libraries that are known for good security practices and, importantly, make sure they are configured correctly to prevent these attacks.</li></ul><h3>The Shift Towards More Secure Alternatives</h3><p>Given these vulnerabilities, there is a growing movement within the developer community to seek more secure alternatives to JWT. One such alternative is PASETO (Platform Agnostic Security Tokens), which removes the ability of the token issuer to dictate the algorithm used for signing, thereby eliminating a significant vector for attacks.</p><h3>What is PASETO?</h3><p>PASETO (Platform Agnostic Security Token) has rapidly gained recognition as a formidable alternative to the widely used JSON Web Tokens (JWT). This recognition stems from its robust security features and its simplified approach to design. A key advantage of PASETO is its ability to address critical challenges commonly associated with JWT, particularly in the areas of cryptographic algorithm selection and management.</p><p>PASETO tokens are structured into three main components:</p><ul><li><strong>Header</strong>: This part of the token specifies its version and purpose. The purpose can either be ‘local’ for encrypted tokens or ‘public’ for tokens that are signed.</li><li><strong>Payload</strong>: Contains the data or claims the token is meant to convey.</li><li><strong>Footer</strong>: Optional section used for additional non-sensitive information that might be needed by the token processing entity.</li></ul><p>With PASETO, developers don’t have to navigate through a myriad of cryptographic options. Instead, they can select from predefined versions, each equipped with a carefully chosen set of robust and secure cryptographic tools. This approach minimizes complexity and reduces the potential for errors in managing cryptographic functions, making it a highly reliable and straightforward choice for secure application development.</p><ul><li><strong>PASETO Version 1:</strong> This version is designed for systems that need to maintain compatibility with older cryptographic standards. It’s ideal for legacy systems that require a balance between old and new security practices.</li><li><strong>PASETO Version 2:</strong> Emphasizes the use of modern, secure cryptographic techniques. This version is suitable for the majority of contemporary applications, providing enhanced security without the complexity of traditional token systems.</li><li><strong>PASETO Version 3:</strong> Tailored for systems that must adhere to NIST (National Institute of Standards and Technology) standards, ensuring compliance with governmental and international security guidelines.</li><li><strong>PASETO Version 4:</strong> Targets modern systems that demand the highest level of security and efficiency. This version is for those seeking the forefront of cryptographic innovation and performance.</li></ul><h3>PASETO Version 1</h3><p>PASETO (Platform Agnostic Security Tokens) Version 1 is tailored for systems that require compatibility with older cryptographic practices but seek to maintain robust security standards.</p><p>Here’s a detailed breakdown of how PASETO Version 1 works, using both its Local and Public modes:</p><h4>Sequence of Operations</h4><ol><li><strong>User Provides Credentials: </strong>The interaction begins with the user entering their credentials (username and password) into a client application.</li><li><strong>Client Requests PASETO v1 Token: </strong>The client sends these credentials to the server, specifically requesting a PASETO Version 1 token. This request includes the credentials and indicates the desired version of PASETO.</li><li><strong>Server Verifies Credentials: </strong>Upon receipt, the server checks the credentials against its database to authenticate the user.</li><li><strong>Database Returns User Data: </strong>If the credentials are authenticated successfully, the database provides the user data back to the server. This data typically includes user identity and other relevant information.</li><li><strong>Server Issues PASETO v1 Token: </strong>Depending on the operational mode required: In Version 1, the <strong>Local Mode</strong> utilizes a symmetric key for encrypting and authenticating the token using AES256 CTR for encryption and HMAC SHA384 for authentication, following the AEAD approach. This ensures that the token can only be decrypted and verified by entities possessing the symmetric key, securing internal communications. Conversely, the <strong>Public Mode</strong> employs RSA PSS with SHA384 to sign the token, enabling external parties with access to the public key to verify the token. This is particularly beneficial for scenarios where tokens need validation by external services, enhancing security and interoperability across different platforms.</li><li><strong>Client Receives PASETO v1 Token: </strong>The client receives the PASETO token and stores it securely, typically for session management or as a credential for future requests.</li><li><strong>User Requests Protected Resource: </strong>To access a protected resource, the user (through the client) sends a request to the server that includes the PASETO token. This is typically done by attaching the token in the authorization header of the request.</li><li><strong>Server Validates PASETO v1 Token: </strong>The server retrieves the token from the request and proceeds with validation, In PASETO Version 1, the validation process differs based on the mode used. In Local Mode, the server decrypts the token using the same symmetric key that was used for its encryption and subsequently verifies both its integrity and authenticity, ensuring that the token has not been tampered with and is still valid. In Public Mode, the server verifies the token’s signature using the public key that corresponds to the private key initially used for signing, allowing for the authentication of the token’s origin and ensuring its integrity without revealing sensitive encryption keys.</li><li><strong>Access Granted to Protected Resource: </strong>If the token is valid, the server grants the client access to the requested protected resource. The server sends the protected resource back to the client.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*Qa-u_8eUYbi_BdqT" /><figcaption>The following sequence describes how a JSON Web Token (JWT) is typically used in client-server communication for authentication and authorization purposes.</figcaption></figure><h3>PASETO Version 2: Enhanced Security for Modern Systems</h3><p>It’s ideal For contemporary systems equipped with the latest cryptographic technologies.</p><ul><li><strong>Encryption (Local Mode):</strong> PASETO Version 2 harnesses the power of XChaCha20-Poly1305, an advanced variant of ChaCha20-Poly1305, to provide top-tier encryption solutions. This choice ensures robust security for applications requiring high-level encryption.</li><li><strong>Signing (Public Mode):</strong> This version adopts Ed25519 for digital signatures. Ed25519 is an efficient version of EdDSA that utilizes the Curve25519 elliptic curve, making it a prime choice for secure digital signing processes.</li></ul><h3>PASETO Version 3: Aligning with NIST Standards for Enhanced Compatibility</h3><p>Designed For systems needing compliance with NIST (National Institute of Standards and Technology) standards.</p><ul><li><strong>Encryption (Local Mode):</strong> Version 3 of PASETO introduces AES-256-GCM for authenticated encryption, a contemporary standard that surpasses AES-256-CTR. This encryption method is widely endorsed for new applications due to its security efficiency and compliance suitability.</li><li><strong>Signing (Public Mode):</strong> It capitalizes on ECDSA using the NIST P-384 curve coupled with SHA-384. This configuration is specifically tailored for organizations that require adherence to NIST guidelines, providing a reliable and compliant signing option.</li></ul><h3>PASETO Version 4: Prioritizing Cutting-edge Security and Efficiency</h3><p>Designed For modern systems that demand the forefront of security technology and operational efficiency.</p><ul><li><strong>Encryption (Local Mode):</strong> Similar to Version 2, PASETO Version 4 utilizes XChaCha20-Poly1305 for encryption, ensuring exceptional security and performance levels. This encryption choice is ideal for systems that prioritize both security and high-speed operation.</li><li><strong>Signing (Public Mode):</strong> This version continues to use Ed25519 for digital signatures, maintaining a high standard of security combined with efficient verification. This makes it suitable for environments where fast and reliable security verification is critical.</li></ul><h3>Enhanced Security Features</h3><p>PASETO’s design inherently protects against several common security issues found in JWT:</p><ul><li><strong>Non-trivial Forgery</strong>: By removing the algorithm header found in JWT, PASETO prevents attackers from manipulating the token processing behavior, such as forcing the use of a weaker algorithm.</li><li><strong>Complete Data Authentication</strong>: All data within a PASETO token is authenticated using AEAD, making unauthorized modifications impossible.</li><li><strong>Encrypted Payloads</strong>: In local mode, the payload is encrypted rather than merely encoded, which protects sensitive information from unauthorized access.</li></ul><p>PASETO addresses many of the security concerns that plague JWTs. It is designed to be more secure by default and does not allow for the flexibility of choosing insecure or deprecated algorithms.</p><ol><li><strong>Simplicity and Security</strong>: PASETO simplifies token usage and reduces the chances of misconfiguration that can lead to security vulnerabilities.</li><li><strong>Versioned Protocols</strong>: Each PASETO token contains a version corresponding to a specific set of rules for its creation and validation.</li><li><strong>Clear Distinction Between Local and Public Tokens</strong>: PASETO clearly distinguishes between tokens encrypted (local) and signed (public).</li></ol><h3>When Not to Use PASETO</h3><p>PASETOs (Platform-Agnostic Security Tokens) are designed to enhance security in many scenarios, but it’s crucial to recognize situations where they may not be the best fit. One particular use case where PASETOs fall short is in scenarios requiring reusable tokens.</p><h4>Non-reusability of PASETOs</h4><p>PASETOs are intentionally designed to be single-use tokens without mechanisms to prevent replay attacks. If an attacker manages to intercept a valid PASETO, they could potentially reuse it to forge multiple valid requests. This misuse directly contradicts the intended use of PASETOs, which should be limited to a one-time authentication or authorization check.</p><h4>The Inappropriateness for Long-Lived Access Tokens</h4><p>Specifically, PASETOs are unsuitable for long-lived access tokens in web authentication flows, such as those commonly seen with JSON Web Tokens (JWTs).</p><p>Here’s a typical JWT-based authentication flow to illustrate this point:</p><ol><li><strong>User Login:</strong> A user submits their username and password to a website.</li><li><strong>Credential Validation:</strong> The website checks the credentials and, if valid, issues a JWT that contains user information and sets an expiration (e.g., one day).</li><li><strong>Token Storage:</strong> The user stores this JWT in their browser.</li><li><strong>Subsequent Requests:</strong> For future requests, the user sends this JWT back to the website as proof of identity.</li><li><strong>Token Validation:</strong> The website verifies the JWT locally — checking for tampering and expiration — before fulfilling the request.</li></ol><p>In this flow, the JWT serves as a multi-use identity proof, which is exactly what PASETOs are designed to avoid. Using a PASETO in such a scenario would not prevent an attacker who has obtained the token from using it multiple times, thus impersonating the user or causing other security issues.</p><h4>Security Implications</h4><p>Many developers choose token-based authentication to eliminate the need for server-side session management, thereby enhancing application performance. However, this approach can expose the application to risks of token abuse and replay attacks. While JWTs can be designed to include mechanisms like expiration and not-before timestamps to mitigate some risks, PASETOs lack these capabilities and are strictly single-use.</p><h3>PASETO vs JWT</h3><p>When comparing PASETO (Platform-Agnostic Security Tokens) with JWT (JSON Web Tokens), several key differences highlight the strengths and potential drawbacks of each approach. These differences are crucial for developers when choosing the right security token framework for their applications.</p><h4>Security Enhancements in PASETO</h4><p>PASETO enhances security by constraining the choice of cryptographic algorithms. Unlike JWT, which allows developers to select from a wide array of algorithms ( including some that are considered insecure or deprecated ) PASETO only supports a set of rigorously vetted, secure algorithms. This design philosophy effectively eliminates risks associated with the use of weak or vulnerable cryptographic methods.</p><h4>Reduced Complexity and Misconfiguration Risks</h4><p>JWT’s flexibility, while advantageous in terms of customization, often leads to misconfiguration and security vulnerabilities. Developers must make informed choices about algorithms and settings, but this flexibility can result in critical errors if not handled correctly. In contrast, PASETO’s more restrictive framework simplifies these decisions by offering predefined configurations. This not only streamlines the development process but also significantly reduces the chance of security flaws stemming from improper token setup.</p><h4>Advanced Built-in Features of PASETO</h4><p>PASETO comes equipped with robust features that enhance its usability and security:</p><ul><li><strong>Token Versioning:</strong> PASETO explicitly supports token versioning, making it easier to manage and update tokens safely as standards evolve.</li><li><strong>Purpose Definitions:</strong> PASETO tokens include clear definitions for their intended purposes (e.g., authentication vs. data transfer), which helps prevent misuse in different contexts and adds an additional layer of security.</li></ul><h4>Contemporary Needs and Developer Considerations</h4><p>While JWTs are entrenched in many systems due to their broad support and flexibility, PASETO stands out as a compelling alternative, especially for new projects prioritizing security and simplicity. The predefined nature of PASETO reduces the risk of errors and security breaches, making it an attractive option for developers who want to ensure high security without delving deeply into the complexities of cryptographic protocols.</p><h3>Last word</h3><p>For developers seeking a modern, secure solution for token-based authentication, PASETO is worthy of consideration. It addresses many of the vulnerabilities inherent in JWTs and provides a more streamlined, error-resistant approach to token management. By reducing complexity and focusing on built-in security features, PASETO emerges as a sophisticated alternative that could better meet the needs of contemporary applications requiring robust security measures.</p><p><strong>Learning Resources:</strong></p><p><a href="https://ieeexplore.ieee.org/document/10277377">Performance and Security Comparison of Json Web Tokens (JWT) and Platform Agnostic Security Tokens (PASETO) on RESTful APIs</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsNz0C7HMgtM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsNz0C7HMgtM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsNz0C7HMgtM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/640e7e8390434219f73ccc7f68b81cd9/href">https://medium.com/media/640e7e8390434219f73ccc7f68b81cd9/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fdgg1dvs0Bn4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Ddgg1dvs0Bn4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fdgg1dvs0Bn4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4138215a8e4df8a542fa874e26ea148a/href">https://medium.com/media/4138215a8e4df8a542fa874e26ea148a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f084ed952586" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/breaking-down-paseto-vs-jwt-which-token-is-right-for-you-f084ed952586">Breaking Down PASETO vs. JWT: Which Token is Right for You?</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Harmonious Symphony of the Native American Flute: A Journey into Mind and Spirit]]></title>
            <link>https://medium.com/@teal33t/the-harmonious-symphony-of-the-native-american-flute-a-journey-into-mind-and-spirit-58d1413fa6a4?source=rss-7f2339b3b56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/58d1413fa6a4</guid>
            <category><![CDATA[native-americans]]></category>
            <category><![CDATA[sound-healing]]></category>
            <category><![CDATA[flute]]></category>
            <category><![CDATA[healing]]></category>
            <category><![CDATA[music-therapy]]></category>
            <dc:creator><![CDATA[Saman Esmaeil]]></dc:creator>
            <pubDate>Sat, 01 Jul 2023 14:01:42 GMT</pubDate>
            <atom:updated>2024-04-26T10:17:33.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xt_w0Kl7-5rHas59AcmTNQ.png" /></figure><p>The Native American flute, a wind instrument steeped in the culture of indigenous North American societies, has been revered for its meditative qualities and its role in healing, courtship, work songs, and ceremonial contexts. The flute’s mellifluous notes carry the stories of ancients, whispers of the wind, and the spirit of a rich cultural heritage. Today, its enchanting notes can be found echoing in museum shops, New Age gift stores, and flute circles — community gatherings where individuals, irrespective of their formal music training, can indulge in creating music. The flute’s unique sound, a blend of natural tones and human craftsmanship, resonates with the rhythm of the heart, connecting us with the timeless wisdom of our ancestors and the tranquil echoes of nature.</p><h3>A Deeper Connection: The Native American Flute and Music Therapy</h3><p>Despite its widespread popularity and historical usage in healing contexts, scientific investigation into the therapeutic potential of the Native American flute in music therapy has been scarce. Yet, the few instances where it has been used have yielded promising results. From reducing anxiety in individuals diagnosed with trauma-related disorders to aiding the spiritual journey of a Navajo woman in hospice care, the flute has proven itself as a powerful tool in the hands of music therapists. Yet, the journey of integrating this ancient instrument into the modern practice of music therapy is only beginning. As we delve deeper into the harmonious world of the Native American flute, we may unearth new ways to heal and connect with our inner selves and the world around us.</p><h3>The Science Behind the Serenity</h3><p>A pilot study conducted at the <a href="https://www.flutehaven.com/">Flute Haven Native Flute School</a> found fascinating trends during periods of Native American flute playing. A group of 15 volunteers, each carrying their unique relationship with the flute, embarked on a journey to discover the physiological effects of playing this instrument. The participants, who varied in gender and experience with the flute, showed a slight decrease in heart rate and an increase in blood volume pulse, suggesting vasodilation. This could possibly indicate a reduction in autonomic arousal, hinting at a potential relaxation response.</p><p>Imagine, for a moment, the scene at the Flute Haven Native Flute School. A group of individuals, each holding a Native American flute, creating a symphony of sounds that resonate with the deepest parts of the human spirit. As the melodies fill the room, the heart slows down, beating in harmony with the rhythms of the music. The body responds, blood vessels dilate, and a sense of calm prevails. It is in this symphony of sounds and physiological responses that we witness the potential healing power of the Native American flute.</p><p>Further, there was an observed increase in theta and alpha brain wave frequencies during flute playing. The increase in alpha frequency may be interpreted as a reduction in cognitive activity, aligning with the view that increased alpha rhythms represent a cortical idling state. Imagine your mind, often crowded with thoughts, slowing down its pace to match the tranquil notes of the flute. The incessant chatter of the mind fades away, replaced by the soothing rhythms of the music. The brain relaxes, reflected in the increase of alpha waves, signifying a state of calm and relaxation. The enhancement in alpha and slow-wave frequencies may serve as markers of relaxation or meditative states.</p><h3>The Music of Healing: A New Horizon in Music Therapy</h3><p>These findings suggest the possibility of the Native American flute eliciting a relaxation response, which could be further harnessed in music therapy. The instrument’s meditative qualities, coupled with its potential physiological effects, could provide a unique and effective approach to promoting relaxation and well-being.</p><p>In an effort to fill this research gap, an exploratory pilot study was conducted at the Flute Haven Native Flute School with 15 volunteer Native American flute players. Participants were monitored for autonomic measures and electroencephalogram (EEG) activity while playing the flute.</p><p><a href="https://ui.adsabs.harvard.edu/abs/2014arXiv1401.6004M/abstract">The study</a> found that playing the Native American flute led to a slight decrease in mean heart rate, from 72.76 to 71.69 BPM, and a significant increase in blood volume pulse, suggesting a potential reduction in autonomic arousal. EEG results showed significant increases in theta (4–8 Hz) and alpha (8–12 Hz) frequencies during flute playing, indicating a possible reduction in cognitive activity. These findings suggest that playing the Native American flute could potentially elicit a relaxation response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*SmcrvhvNsHw4oBHEfZIZtQ.png" /></figure><p>This research opens up avenues for further exploration, paving the way for a deeper understanding of the physiological mechanisms underlying the traditional uses of these instruments for healing. The Native American flute, with its potential to induce relaxation responses and to impact physiological metrics, offers a fascinating blend of tradition and science. Its potential in music therapy is vast and largely unexplored, and it is our responsibility to delve into this potential to unearth the healing power that lies within.</p><p>Further research with larger samples and more refined measures could provide more insights into the therapeutic potential of the Native American flute. Such research could include studying the effects of flute playing on different demographics, exploring its impact on various physiological parameters, and investigating its potential applications in treating specific health conditions. These studies could help create a comprehensive body of knowledge that could then be used to effectively integrate the Native American flute into therapeutic practices.</p><h3>The Ancient Melodies in Modern Times</h3><p>In today’s fast-paced world, stress and anxiety are common companions. In this context, the Native American flute brings with it a promise of tranquility and peace. Its soothing sounds can transport us to a serene space, far from the madding crowd, where we can reconnect with ourselves and discover a sense of calm. The Native American flute invites us to pause, listen, and allow the ancient melodies to heal and rejuvenate us.</p><p>A prime example of this calming, meditative influence can be found in the music of Carlos Nakai. Nakai, of Navajo-Ute heritage, is one of the most celebrated Native American flute players of our time. His discography spans over three decades and includes more than 50 albums. With the enchanting notes of his flute, Nakai takes listeners on a journey that transcends time and space, to a realm of peace and tranquility.</p><p>Nakai’s albums like “Canyon Trilogy” or “Island Of Bows” are excellent representations of his unique style. These tracks meld the traditional sounds of the Native American flute with a modern ambiance, creating an ethereal soundscape that calms the mind and soothes the spirit. Each melody tells a story, evoking images of vast landscapes, serene canyons, and the timeless beauty of nature.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrP9uuuhEx5M%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrP9uuuhEx5M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrP9uuuhEx5M%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bd2ed066c3c0b92f9d0ab1afdaf6f0a/href">https://medium.com/media/9bd2ed066c3c0b92f9d0ab1afdaf6f0a/href</a></iframe><p>But the therapeutic effects of the Native American flute extend beyond passive listening. The act of playing this instrument can also be a mindful practice. As the player breathes life into the flute, they create a melody that is uniquely their own. This process draws attention to the present moment, helping to anchor the player in the here and now. The focus required to play the Native American flute can help to tune out external distractions, fostering an increased awareness of one’s thoughts, emotions, and physical sensations.</p><h3>The Ancient Melodies: A Prayer for Modern Times</h3><p>The Native American flute, an ethnic wind instrument steeped in rich cultural history, has long been a symbol of peace and healing. Its dulcet tones, reminiscent of the whispering wind and flowing rivers, have the ability to transport listeners to a realm of tranquility, akin to a prayer for inner peace. The haunting melodies of the flute serve as a powerful antidote to our modern lives’ stress and anxiety.</p><p>Musicians like Carlos Nakai have beautifully demonstrated the flute’s potential in creating soulful compositions that evoke deep emotions. His music, a blend of traditional Native American tunes and contemporary elements, showcases the flute’s versatility and its ability to bridge the ancient with the modern.</p><h3>The Art of Playing: Breathing Life into the Flute</h3><p>To play the Native American flute is to engage in a dance with one’s breath — a delicate balancing act of inhalation and exhalation that brings the flute to life. This dance is not just about creating music but also a form of meditation, a practice of mindfulness that anchors us in the present moment.</p><p>One such breathing technique that has shown immense potential for Native American flute players is Kapalabhati, a yogic practice known as the “breath of fire”. This technique’s rapid, forceful exhalations and passive inhalations enhance the player’s breath control, enabling them to produce clearer, more powerful notes. Moreover, the practice of Kapalabhati can infuse the act of playing with a sense of energy and vitality, adding a new dimension to the performance.</p><p>Kapalabhati, also known as the “shining skull breath” or “breath of fire,” is a traditional yogic breathing technique that has been practiced for thousands of years. The method involves short, powerful exhales and passive inhales. It is known for its ability to cleanse the respiratory system, energize the body, and sharpen the mind.</p><p>In the context of playing the Native American flute, Kapalabhati can be a game-changer. By practicing this breathing technique, players can gain better control over their exhalation, which directly impacts the tone and intensity of the notes played. The sharp, forceful exhalations of Kapalabhati can help in producing clear, powerful notes, while the passive inhalations can train the player to quickly and efficiently draw breath between notes or phrases.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F52TOhE94fEg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D52TOhE94fEg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F52TOhE94fEg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b1f09541c1cbbc2a22884cda60ba0d5/href">https://medium.com/media/8b1f09541c1cbbc2a22884cda60ba0d5/href</a></iframe><h3>The Flute as a Prayer: A Path to Self-Discovery and Healing</h3><p>In Native American cultures, playing the flute is often likened to praying. Each note is an invocation, a plea to the universe for harmony and balance. The music created is a reflection of the player’s inner state, their hopes, dreams, and fears laid bare. This vulnerability, this act of raw self-expression, can be a potent tool for personal growth and healing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N9s567hN6VPrbgL9PLqoDQ.png" /></figure><h3>Conclusion</h3><p>The Native American flute, with its rich cultural history and soothing tones, is emerging as a promising tool in music therapy. Its potential to induce relaxation responses and to impact physiological metrics offers a fascinating blend of tradition and science. As we continue to explore the healing power of music, the Native American flute stands as a testament to the fact that sometimes, the keys to our well-being can be found in the harmonious notes of our past.</p><p><em>Are you a music therapist or a wellness enthusiast interested in the healing power of music? Follow me (</em><a href="https://www.instagram.com/soundofniru/"><em>soundofniru</em></a><em>) to stay updated on the latest NAF music and research and discussions on music therapy, well-being, and the fascinating world of the Native American flute. Follow my NAF musics on </em><a href="https://www.instagram.com/soundofniru/"><em>Instagram</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58d1413fa6a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code in PHP: Best Practices and Principles]]></title>
            <link>https://medium.com/@teal33t/clean-code-in-php-best-practices-and-principles-8ccf2f1673a7?source=rss-7f2339b3b56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ccf2f1673a7</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Saman Esmaeil]]></dc:creator>
            <pubDate>Wed, 28 Jun 2023 20:36:16 GMT</pubDate>
            <atom:updated>2025-02-22T22:19:26.788Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VpshknO2LKmROQyXN_8nsA.png" /><figcaption>Image generated by DALL-E</figcaption></figure><p>Clean code is the foundation of good software development. It is the art of writing code that is easy to read, understand, and maintain. In this article, we will discuss what clean code is and its importance, the best practices and principles to write clean code in PHP, and examples of bad and good code. We will also consider some of the famous quotes of Uncle Bob, one of the pioneers of clean code.</p><blockquote>Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control. — Uncle Bob.</blockquote><p>As PHP developers, we have the responsibility to write clean code that is not only functional but also maintainable. Clean code is essential because it reduces technical debt, improves code quality, and makes it easier for new developers to understand and contribute to the project. In this article, we will discuss the best practices and principles to write clean code in PHP.</p><h3>Principle 1: Code should be easy to read</h3><blockquote>Indeed, the ratio of time spent reading versus writing is well over 10 to 1. We are constantly reading old code as part of the effort to write new code.— Robert C. Martin</blockquote><p>The first principle of writing clean code is to make it easy to read. Code is read far more often than it is written, so making it easy to read will save time and reduce errors. To achieve this, you should use meaningful variable and function names, as well as proper indentation and formatting.</p><p><strong>Bad Practice:</strong></p><pre>function x($a){$b=0;for($i=0;$i&lt;count($a);$i++){$b+=$a[$i];}return $b;}</pre><p><strong>Good Practice:</strong></p><pre>function sumArray($numbers) {<br>    $total = 0;<br>    for ($i = 0; $i &lt; count($numbers); $i++) {<br>        $total += $numbers[$i];<br>    }<br>    return $total;<br>}</pre><h3>Principle 2: Code should be DRY</h3><blockquote>Every piece of knowledge must have a single, unambiguous, authoritative representation within a system. — Robert C. Martin</blockquote><p>The DRY (Don’t Repeat Yourself) principle means that you should not have redundant code in your application. If you find yourself copying and pasting code, you should refactor it into a reusable function or class. This will reduce errors and make your code easier to maintain.</p><p><strong>Bad Practice:</strong></p><pre>function calculate_area_rectangle($length, $width) {<br>  $area = $length * $width;<br>  return $area;<br>}<br><br>function calculate_perimeter_rectangle($length, $width) {<br>  $perimeter = 2 * ($length + $width);<br>  return $perimeter;<br>}</pre><p><strong>Good Practice:</strong></p><pre>function calculate_rectangle_properties($length, $width) {<br>  $area = $length * $width;<br>  $perimeter = 2 * ($length + $width);<br><br>  return array(&quot;area&quot; =&gt; $area, &quot;perimeter&quot; =&gt; $perimeter); //Returns an array with both values<br>}<br><br>//Or, if you only needed area/perimeter, a combined function with parameter<br>function calculate_rectangle($length, $width, $property){<br>    if($property == &quot;area&quot;){<br>        return $length * $width;<br>    }<br>    if($property == &quot;perimeter&quot;){<br>        return 2 * ($length + $width);<br>    }<br>    return null;<br>}</pre><h3>Principle 3: Code should be modular</h3><blockquote>The secret to building large apps is never build large apps. Break your applications into small pieces. Then, assemble those testable, bite-sized pieces into your big application. — Justin Meyer</blockquote><p>Modularity is the cornerstone of clean coding. In PHP, this means breaking your code into smaller, reusable pieces known as modules or functions. These modules should have a single responsibility and should be independent. This not only makes your code more readable but also makes it easier to test and maintain.</p><p><strong>Bad Practice:</strong></p><pre>function userRegistration($firstName, $lastName, $email, $password) {<br>    // Validate input<br>    if (empty($firstName) || empty($lastName) || empty($email) || empty($password)) {<br>        return false;<br>    }<br>    // Create user<br>    $user = new User();<br>    $user-&gt;firstName = $firstName;<br>    $user-&gt;lastName = $lastName;<br>    $user-&gt;email = $email;<br>    $user-&gt;password = $password;<br>    // Save user<br>    $user-&gt;save();<br>    // Send welcome email<br>    $mailer = new Mailer();<br>    $mailer-&gt;sendWelcomeEmail($email);<br>    return true;<br>}</pre><p><strong>Good Practice:</strong></p><pre>function validateInput($firstName, $lastName, $email, $password) {<br>    return !empty($firstName) &amp;&amp; !empty($lastName) &amp;&amp; !empty($email) &amp;&amp; !empty($password);<br>}<br><br>function createUser($firstName, $lastName, $email, $password) {<br>    $user = new User();<br>    $user-&gt;firstName = $firstName;<br>    $user-&gt;lastName = $lastName;<br>    $user-&gt;email = $email;<br>    $user-&gt;password = $password;<br>    return $user-&gt;save();<br>}<br><br>function sendWelcomeEmail($email) {<br>    $mailer = new Mailer();<br>    $mailer-&gt;sendWelcomeEmail($email);<br>}<br><br>function userRegistration($firstName, $lastName, $email, $password) {<br>    if (validateInput($firstName, $lastName, $email, $password)) {<br>        if (createUser($firstName, $lastName, $email, $password)) {<br>            sendWelcomeEmail($email);<br>            return true;<br>        }<br>    }<br>    return false;<br>}</pre><h3>Principle 4: Code should be efficient</h3><blockquote>Programs must be written for people to read, and only incidentally for machines to execute. — Hal Abelson</blockquote><p>Efficient code is not only about speed and performance but also about how well your code utilizes resources. Writing efficient PHP code involves understanding the cost of operations, avoiding unnecessary calculations, and using the right data structures and algorithms for the job. Remember, premature optimization is the root of all evil. Don’t optimize until you have a proven bottleneck.</p><p><strong>Bad Practice:</strong></p><pre>function findElement($array, $element) {<br>    for ($i = 0; $i &lt; count($array); $i++) {<br>        if ($array[$i] === $element) {<br>            return true;<br>        }<br>    }<br>    return false;</pre><p><strong>Good Practice:</strong></p><pre>function findElement($array, $element) {<br>    return in_array($element, $array);<br>}</pre><h3>Principle 5: Code should be robust and handle errors gracefully</h3><blockquote>Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.— Rich Cook</blockquote><p>Robust code is code that can handle unexpected inputs or situations without crashing or behaving unpredictably. This involves validating inputs, handling exceptions properly, and providing meaningful error messages.</p><p><strong>Bad Practice:</strong></p><pre>function divide($num1, $num2) {<br>    return $num1 / $num2;<br>}</pre><p><strong>Good Practice:</strong></p><pre>function divide($num1, $num2) {<br>    if ($num2 == 0) {<br>        throw new InvalidArgumentException(&quot;Cannot divide by zero.&quot;);<br>    }<br>    return $num1 / $num2;<br>}</pre><h3>Principle 6: Code should be testable</h3><blockquote>Any fool can write code that a computer can understand. Good programmers write code that humans can understand.— Martin Fowler</blockquote><p>Testability is another crucial aspect of clean code. Code should be designed in a way that makes it easy to test automatically using unit tests. This means creating functions and classes that have clear inputs and outputs, avoiding hidden dependencies, and making sure that each piece of code does one thing well.</p><p><strong>Bad Practice:</strong></p><pre>class Order {<br>    public function calculateTotal() {<br>        $total = 0;<br>        foreach ($this-&gt;items as $item) {<br>            $total += $item-&gt;price;<br>        }<br>        $this-&gt;applyDiscount($total);<br>        return $total;<br>    }<br>    private function applyDiscount(&amp;$total) {<br>        $total *= 0.9;<br>    }<br>}</pre><p><strong>Good Practice:</strong></p><pre>class Order {<br>    public function calculateTotal() {<br>        $total = 0;<br>        foreach ($this-&gt;items as $item) {<br>            $total += $item-&gt;price;<br>        }<br>        return $this-&gt;applyDiscount($total);<br>    }<br>    private function applyDiscount($total) {<br>        return $total * 0.9;<br>    }<br>}</pre><h3>Principle 7: Code should follow a coding standard</h3><blockquote>The purpose of software engineering is to control complexity, not to create it. — Pamela Zave</blockquote><p>Following a coding standard or style guide helps to ensure that the code is consistent and easy to read. It can also help to prevent certain types of errors. For PHP, a commonly used standard is the PSR-2 coding standard, which covers things like indentation, spacing, and naming conventions.</p><p><strong>Bad Practice:</strong></p><pre>class myClass {<br>    private $myProperty;<br><br>    function myFunction() {<br>        // ...<br>    }<br>}</pre><p><strong>Good Practice:</strong></p><pre>class MyClass {<br>    private $myProperty;<br><br>    public function myFunction() {<br>        // ...<br>    }<br>}</pre><h3>Principle 8: Code should be well-documented</h3><blockquote>Good code is its own best documentation. As you’re about to add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed? — Steve McConnell</blockquote><p>While good code should be self-explanatory, comments and documentation are still important, especially for complex algorithms or important business logic. Comments should explain why something is done, not what is done. In addition to comments, PHPDoc blocks can be used to provide structured documentation for classes, methods, and variables.</p><p><strong>Bad Practice:</strong></p><pre>// Adds 1 to the number<br>function addOne($num) {<br>    return $num + 1;<br>}</pre><p><strong>Good Practice:</strong></p><pre>/**<br> * Increments the given number by one.<br> *<br> * @param int $num The number to increment.<br> * @return int The incremented number.<br> */<br>function increment($num) {<br>    return $num + 1;<br>}</pre><p>Remember, clean code is not a destination but a journey. It’s apractice and mindset that requires continuous learning, adaptation, and improvement. As Uncle Bob stated, “You know you are working on clean code when each routine you read turns out to be pretty much what you expected.” This is what we should strive for — a codebase that feels comfortable and intuitive, as if it’s a well-written prose.</p><p>Ultimately, the quest for writing clean code is about respect — respect for yourself, respect for your co-workers, respect for the code, and most importantly, respect for the users who will interact with your software.</p><p>By adhering to the principles outlined in this article, you will be well on your way to becoming a better PHP developer. However, these principles are not limited to PHP, they can be applied to any programming language. So, no matter what language you are using, remember to always strive for clean code.</p><p><strong>New Article, Next Up</strong>: Dive deeper into securing PHP applications with actionable strategies in <a href="https://medium.com/@teal33t/9-essential-practices-for-secure-php-coding-9a1b15d45c1b"><strong>9 Essential Practices for Secure PHP Coding</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ccf2f1673a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s New in PHP 8.1,]]></title>
            <link>https://medium.com/@teal33t/whats-new-in-php-8-1-ddc40ce9bf7b?source=rss-7f2339b3b56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddc40ce9bf7b</guid>
            <category><![CDATA[php-8]]></category>
            <category><![CDATA[phpunit]]></category>
            <category><![CDATA[php-developers]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[php-development]]></category>
            <dc:creator><![CDATA[Saman Esmaeil]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 10:58:59 GMT</pubDate>
            <atom:updated>2023-02-21T11:24:27.342Z</atom:updated>
            <content:encoded><![CDATA[<h3>What’s New in PHP 8.1 : Discover the Latest Features, Including Readonly Properties and Explicit Octal Notation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GQ6kthP0xqHUwksIvqcROA.png" /></figure><p>PHP is one of the most widely used server-side programming languages that is constantly evolving with new features and improvements. The stable release, <a href="https://www.php.net/releases/8.1/en.php">PHP 8.1</a>, is no exception. It introduces several new features and improvements that help developers write better, cleaner, and more secure code.</p><p>In this article, we’ll take a look at some of the new features in PHP 8.1 and provide examples to help you understand how to use them.</p><p><strong>Pure Intersection Types:</strong></p><p>PHP 8.1 introduces pure intersection types, which allow for more precise type declarations. A pure intersection type is formed by intersecting two or more class/interface types. This feature can be useful when working with complex class hierarchies.</p><p>Here’s an example:</p><pre>interface A {<br>    public function foo(): void;<br>}<br><br>interface B {<br>    public function bar(): void;<br>}<br><br>function baz(A&amp;B $ab): void {<br>    $ab-&gt;foo();<br>    $ab-&gt;bar();<br>}<br><br>class C implements A, B {<br>    public function foo(): void {}<br>    public function bar(): void {}<br>}<br><br>$object = new C();<br>baz($object);</pre><p>In the above example, we define two interfaces A and B. We then define a function baz that takes an argument of type A&amp;B. Finally, we create a class C that implements both interfaces A and B and pass an object of that class to the baz function.</p><p><strong>Enums:</strong></p><p>Enums are a new type of data structure in PHP 8.1. They provide a way to define a fixed set of named values. Enums can be useful when you want to represent a set of values that are mutually exclusive.</p><p>Here’s an example:</p><pre>enum Animal {<br>    case DOG;<br>    case CAT;<br>    case BIRD;<br>}<br><br>function processAnimal(Animal $animal): void {<br>    switch ($animal) {<br>        case Animal::DOG:<br>            echo &quot;Processing dog\n&quot;;<br>            break;<br>        case Animal::CAT:<br>            echo &quot;Processing cat\n&quot;;<br>            break;<br>        case Animal::BIRD:<br>            echo &quot;Processing bird\n&quot;;<br>            break;<br>    }<br>}<br><br>processAnimal(Animal::DOG);</pre><p>In the above example, we define an Animal enum with three named values: DOG, CAT, and BIRD. We then define a function processAnimal that takes an argument of type Animal and uses a switch statement to process each animal.</p><p><strong>The </strong><strong>never Return Type:</strong></p><p>The never return type is a new feature in PHP 8.1 that indicates that a function will never return. This can be useful when working with code that throws exceptions or when dealing with infinite loops.</p><p>Here’s an example:</p><pre>function doSomething(): never {<br>    throw new Exception(&#39;Something went wrong&#39;);<br>}<br><br>function infiniteLoop(): never {<br>    while (true) {}<br>}<br><br>try {<br>    doSomething();<br>} catch (Exception $e) {<br>    echo $e-&gt;getMessage() . &quot;\n&quot;;<br>}<br><br>infiniteLoop();</pre><p>In the above example, we define two functions doSomething and infiniteLoop. The doSomething function throws an exception, which means it will never return. The infiniteLoop function contains an infinite loop, which also means it will never return.</p><p><strong>Fibers:</strong></p><p>Fibers are a new feature in PHP 8.1, which provide a lightweight alternative to threads. They are user-land cooperative multitasking, meaning that they allow you to pause a function at a certain point and continue it later, while another function is executing.</p><p>Fibers can be created and managed using the Fiber class. Here is an example of how to use fibers to perform a long-running task without blocking the main program:</p><pre>function longRunningTask(int $n): Fiber {<br>    return new Fiber(function() use ($n) {<br>        $result = 0;<br>        for ($i = 1; $i &lt;= $n; $i++) {<br>            $result += $i;<br>            Fiber::yield();<br>        }<br>        return $result;<br>    });<br>}<br><br>$fiber = longRunningTask(1000000);<br>while ($fiber-&gt;status() == Fiber::STATUS_SUSPENDED) {<br>    $fiber-&gt;resume();<br>}<br>echo $fiber-&gt;getReturn();</pre><p>In this example, the longRunningTask() function returns a new Fiber that calculates the sum of numbers from 1 to a given number $n. The calculation is done in a loop, with the Fiber yielding after each iteration to allow other tasks to run.</p><p>The main program creates a new Fiber using the longRunningTask() function and then enters a loop that repeatedly resumes the Fiber until it has completed its task. Finally, the main program prints the result of the calculation.</p><p><strong>New </strong><strong>readonly Properties</strong></p><p>PHP 8.1 introduces support for readonly properties, which can only be set during object initialization and then cannot be modified. Readonly properties provide a safe and efficient way to ensure that certain object properties remain constant throughout the object&#39;s lifetime.</p><p>Here is an example of how to define and use a readonly property:</p><pre>class MyClass {<br>    public readonly string $name;<br><br>    public function __construct(string $name) {<br>        $this-&gt;name = $name;<br>    }<br>}<br><br>$obj = new MyClass(&#39;John&#39;);<br>echo $obj-&gt;name; // prints &#39;John&#39;<br>$obj-&gt;name = &#39;Bob&#39;; // error: cannot modify readonly property</pre><p>In this example, the MyClass class has a readonly property $name, which is initialized during object construction and then cannot be modified. The __construct() method sets the value of $name to the provided argument.</p><p><strong>Define final Class Constants</strong></p><p>PHP 8.1 allows you to define final class constants, which are constants that cannot be overridden by subclasses. Final class constants provide a way to ensure that certain constant values remain constant throughout the entire class hierarchy.</p><p>Here is an example of how to define and use a final class constant:</p><pre>class Math {<br>    public final const PI = 3.14159;<br>}<br><br>echo Math::PI; // prints 3.14159<br>Math::PI = 3.14; // error: cannot modify final class constant</pre><p>In this example, the Math class has a final constant PI, which is set to the value 3.14159. The constant can be accessed using the class name (Math::PI), but it cannot be modified at runtime.</p><p><strong>New </strong><strong>fsync() and </strong><strong>fdatasync() Functions</strong></p><p>The file synchronization operation ensures that data written to a file is physically stored on a persistent storage device. PHP 8.1 introduced two new functions to perform file synchronization operations:</p><ul><li>fsync(): Synchronize a file’s in-core state with its storage device.</li><li>fdatasync(): Synchronize only the file’s data with its storage device.</li></ul><p>These functions are helpful for database management systems and transactional file systems.</p><p>Here’s an example of using the fsync() function:</p><pre>$file = fopen(&quot;test.txt&quot;, &quot;w&quot;);<br>fwrite($file, &quot;Hello, World!&quot;);<br>fsync($file);<br>fclose($file);</pre><p>The code writes a string to the test.txt file and then synchronizes its in-core state with the storage device using the fsync() function.</p><p>Here’s an example of using the fdatasync() function:</p><pre>$file = fopen(&quot;test.txt&quot;, &quot;w&quot;);<br>fwrite($file, &quot;Hello, World!&quot;);<br>fdatasync($file);<br>fclose($file);</pre><p>The code writes a string to the test.txt file and then synchronizes only its data with the storage device using the fdatasync() function.</p><p><strong>New </strong><strong>array_is_list() Function</strong></p><p>PHP 8.1 introduced a new function called array_is_list(), which checks if an array is a list.</p><p>An array is a list if it has sequential numeric keys starting from 0, and the keys form a contiguous sequence.</p><p>Here’s an example:</p><pre>$array1 = [0 =&gt; &#39;foo&#39;, 1 =&gt; &#39;bar&#39;, 2 =&gt; &#39;baz&#39;];<br>$array2 = [0 =&gt; &#39;foo&#39;, 2 =&gt; &#39;bar&#39;, 4 =&gt; &#39;baz&#39;];<br>$array3 = [0 =&gt; &#39;foo&#39;, 1 =&gt; &#39;bar&#39;, 3 =&gt; &#39;baz&#39;];<br>var_dump(array_is_list($array1)); // true<br>var_dump(array_is_list($array2)); // false<br>var_dump(array_is_list($array3)); // false</pre><p>The output of this code is:</p><pre>bool(true)<br>bool(false)<br>bool(false)</pre><p>In this example, $array1 is a list because it has sequential numeric keys starting from 0, and the keys form a contiguous sequence. However, $array2 and $array3 are not lists because they do not meet these criteria.</p><p><strong>New Sodium XChaCha20 Functions</strong></p><p>PHP 7.2 introduced the Sodium cryptographic library, which provides a set of functions for encryption, decryption, hashing, and more.</p><p>PHP 8.1 added new functions to the Sodium library that implement the XChaCha20 cipher, which is an extended version of the ChaCha20 cipher.</p><p>The XChaCha20 cipher provides better security than ChaCha20 and is recommended for use in modern cryptographic protocols.</p><p>Here’s an example of using the new Sodium XChaCha20 functions:</p><pre>$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);<br>$message = &quot;Hello, World!&quot;;<br>$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);<br>$ciphertext = sodium_crypto_secretbox_xchacha20poly1305($message, $nonce, $key);<br>$plaintext = sodium_crypto_secretbox_xchacha20poly1305_open($ciphertext, $nonce, $key);<br>echo $plaintext;</pre><p>The code generates a random key and nonce, encrypts a message using the sodium_crypto_secretbox_xchacha20poly1305() function, and then decrypts the ciphertext using the sodium_crypto_secretbox_xchacha20poly1305_open() function.</p><p><strong>New </strong><strong>IntlDatePatternGenerator Class</strong></p><p>The IntlDatePatternGenerator class is a new class in PHP 8.1. This class helps in generating localized date patterns. It’s used to format dates according to a specific format string that takes into account the user’s locale.</p><p>To use this class, first, you need to create an instance of the IntlDatePatternGenerator class, specifying the locale for which you want to generate the pattern:</p><pre>$generator = new IntlDatePatternGenerator(&#39;en_US&#39;);</pre><p>Once you have an instance of the class, you can generate the pattern using the getBestPattern method. This method takes two parameters: the date type and the length. The date type specifies what kind of date you want to format, such as full date, short date, or long date. The length specifies how long you want the date format to be, such as abbreviated, wide, or narrow.</p><p>Here’s an example that demonstrates how to use the IntlDatePatternGenerator class to generate a date pattern:</p><pre>$generator = new IntlDatePatternGenerator(&#39;en_US&#39;);<br><br>$pattern = $generator-&gt;getBestPattern(IntlDateFormatter::FULL, IntlDateFormatter::LONG);<br><br>$dateFormatter = new IntlDateFormatter(&#39;en_US&#39;, IntlDateFormatter::FULL, IntlDateFormatter::LONG);<br>$dateFormatter-&gt;setPattern($pattern);<br><br>$date = new DateTime();<br>echo $dateFormatter-&gt;format($date);</pre><p>In this example, we first create an instance of the IntlDatePatternGenerator class for the ‘en_US’ locale. Then we use the getBestPattern method to generate a date pattern for a full date with a long length.</p><p>We then create an instance of the IntlDateFormatter class, passing in the ‘en_US’ locale, a full date type, and a long length. We set the date pattern for the formatter to the pattern generated by the IntlDatePatternGenerator.</p><p>Finally, we create a DateTime instance representing the current date and format it using the date formatter. The output will be a string representing the date in the format specified by the date pattern.</p><p>The IntlDatePatternGenerator class is a useful addition to PHP 8.1 for applications that need to format dates according to the user’s locale.</p><p><strong>Support for AVIF Image Format</strong></p><p>PHP 8.1 now includes support for the AVIF image format, which is a new image format that provides better compression than existing formats such as JPEG and PNG. The AVIF format uses the AV1 video codec to compress images, resulting in smaller file sizes while maintaining high image quality.</p><p>To use the AVIF format in PHP 8.1, you need to have the AVIF extension installed. You can install this extension on Ubuntu with:</p><pre>apt install libavif-dev</pre><p>Once the extension is installed, you can use the imagecreatefromavif function to create an image resource from an AVIF image file:</p><pre>$image = imagecreatefromavif(&#39;image.avif&#39;);</pre><p>You can then use this image resource with other GD functions to manipulate the image, such as imagejpeg or imagepng to save the image in other formats.</p><p>The AVIF format is a promising addition to PHP 8.1, as it provides a more efficient way to store and transmit images, resulting in faster loading times and lower bandwidth usage.</p><p><strong>New </strong><strong>$_FILES: </strong><strong>full_path Key for Directory Uploads</strong></p><p>Uploading files has always been a crucial part of web applications. PHP 8.1 comes with an exciting new feature that makes handling uploaded files more comfortable.</p><p>Before PHP 8.1, you could only get the name of the uploaded file from the $_FILES array. But with PHP 8.1, you can access the full path to the file in addition to its name by using the full_path key.</p><p>This new feature can make handling uploaded files easier, especially when working with complex systems or when you need to perform additional actions on the uploaded file.</p><p>Here’s an example:</p><pre>$file = $_FILES[&#39;userfile&#39;][&#39;full_path&#39;];<br>$destination = &#39;/uploads/&#39;;<br>$filename = $_FILES[&#39;userfile&#39;][&#39;name&#39;];<br>$destination .= $filename;<br>if (move_uploaded_file($file, $destination)) {<br>    echo &quot;File successfully uploaded&quot;;<br>} else {<br>    echo &quot;Error uploading file&quot;;<br>}</pre><p>The code above demonstrates how to move an uploaded file to a new location using the full_path key. The uploaded file is first retrieved from the $_FILES array using the full_path key and is then moved to the new location using the move_uploaded_file() function.</p><p>This feature makes it easier to handle uploaded files in PHP and is especially useful for complex web applications that require additional actions to be performed on uploaded files.</p><p><strong>Array Unpacking Support for String-Keyed Arrays</strong></p><p>PHP 8.1 introduces a new feature that allows developers to unpack string-keyed arrays. This feature has been available for numeric keyed-arrays in earlier PHP versions.</p><p>With the new array unpacking feature, you can use the … operator to unpack values from an array. Previously, this was only possible with numeric keys, but in PHP 8.1, it can also be used with string-keyed arrays.</p><p>Consider the following example:</p><pre>$data = [<br>&#39;name&#39; =&gt; &#39;John Doe&#39;,<br>&#39;age&#39; =&gt; 35,<br>&#39;country&#39; =&gt; &#39;USA&#39;,<br>];<br><br>echo implode(&#39;, &#39;, [...$data]);<br>// Output: John Doe, 35, USA</pre><p>In this example, we have a string-keyed array called $data. We can use the … operator to unpack the values from the array and pass them as separate arguments to the implode() function.</p><p>The result is a comma-separated string of the values in the array, John Doe, 35, USA.</p><p>This feature can be useful in situations where you need to pass multiple arguments to a function, but you don’t want to pass an array.</p><p><strong>Explicit Octal Numeral Notation</strong></p><p>In PHP, you can specify numeric values in decimal, hexadecimal, and octal notation. Octal notation is a way of representing a number using the digits 0 through 7.</p><p>In previous versions of PHP, octal notation was indicated by a leading zero (0). However, this notation could lead to confusion and errors because it’s easy to forget to add the leading zero.</p><p>To address this, PHP 8.1 introduces a new notation for octal numbers using the prefix 0o or 0O. This notation makes it clear that the number is in octal format, and it’s less likely to be confused with a decimal number.</p><p>For example:</p><pre>$decimal = 123;<br>$hexadecimal = 0x1a;<br>$octal = 0o17;<br><br>echo $decimal; // Output: 123<br>echo $hexadecimal; // Output: 26<br>echo $octal; // Output: 15</pre><p>In this example, we have three different numeric values specified in decimal, hexadecimal, and octal notation. The octal value is represented using the new 0o notation, which makes it clear that it’s an octal number.</p><p><strong>MurmurHash3 and xxHash Hash Algorithms Support</strong></p><p>PHP 8.1 comes with support for two new hash algorithms: MurmurHash3 and xxHash. Both algorithms are non-cryptographic and designed for fast hashing of data. They are particularly useful for hash table implementations and other similar use cases that require fast and efficient hashing.</p><p>MurmurHash3 is a hash function that is designed to generate high-quality hash values with a low collision rate. It is particularly efficient for hash tables, and has good distribution properties.</p><p>xxHash is a fast non-cryptographic hash function with excellent performance on small keys. It is particularly useful for in-memory data structures, such as hash tables, that require fast hashing.</p><p>To use these hash algorithms in PHP 8.1, you can use the hash() function with the appropriate algorithm name, as follows:</p><pre>$murmurHash = hash(&#39;murmur3&#39;, &#39;hello world&#39;);<br>$xxHash = hash(&#39;xxhash&#39;, &#39;hello world&#39;);</pre><p>These hash algorithms can be useful in a variety of contexts, such as caching, indexing, and data processing, where fast and efficient hashing is required.</p><p><strong>DNS-over-HTTPS (DoH) Support</strong></p><p>PHP 8.1 includes support for DNS-over-HTTPS (DoH), a protocol for performing DNS lookups over HTTPS. This protocol is designed to provide enhanced security and privacy for DNS lookups, as it encrypts DNS queries and responses and prevents them from being intercepted or modified in transit.</p><p>To perform a DNS lookup using DoH in PHP 8.1, you can use the new dns_get_record() option DNS_OVER_HTTPS, as follows:</p><pre>$records = dns_get_record(&#39;example.com&#39;, DNS_A, [ &#39;options&#39; =&gt; [ &#39;doh&#39; =&gt; &#39;https://dns.google/dns-query&#39; ] ]);</pre><p>This will perform a DNS lookup for the A record of example.com using the Google DNS-over-HTTPS server. The doh option can be set to any DoH server that supports the standard DoH API.</p><p>DoH can be particularly useful in contexts where privacy and security are a concern, such as in public Wi-Fi networks or in countries where Internet censorship is prevalent.</p><p><strong>File Uploads from Strings with </strong><strong>CURLStringFile</strong></p><p>PHP 8.1 introduces a new feature that allows file uploads from strings with the CURLStringFile class. This class can be used to upload files directly from a string, without having to write the string to a file first.</p><p>To upload a file from a string using CURLStringFile in PHP 8.1, you can use the following code:</p><pre>$data = &#39;This is the contents of my file.&#39;;<br>$filename = &#39;myfile.txt&#39;;<br>$file = new CURLStringFile($data, $filename);<br>$curl = curl_init();<br>curl_setopt($curl, CURLOPT_URL, &#39;http://example.com/upload.php&#39;);<br>curl_setopt($curl, CURLOPT_POSTFIELDS, [&#39;file&#39; =&gt; $file]);<br>$response = curl_exec($curl);</pre><p>This code creates a new CURLStringFile object from a string, and then uses it in a cURL POST request to upload the file to a server.</p><p>This feature can be useful in contexts where file uploads are required, but writing the file to disk first is not desirable or not possible, such as in memory-constrained environments.</p><p><strong>New </strong><strong>MYSQLI_REFRESH_REPLICA Constant</strong></p><p>For PHP 8.1, the MySQLi extension now includes the constant MYSQLI_REFRESH_REPLICA for refreshing replicas of a MySQL cluster. You can use this constant with the mysqli_refresh() method to refresh replicas in a cluster.</p><p>The MYSQLI_REFRESH_REPLICA constant is a more specific option than MYSQLI_REFRESH_SLAVE, which is now deprecated. With MYSQLI_REFRESH_REPLICA, you can refresh one or more replicas in the cluster, while MYSQLI_REFRESH_SLAVE can only refresh all slaves.</p><p>Here’s an example of using the new constant to refresh a single replica:</p><pre>$mysqli = new mysqli(&quot;localhost&quot;, &quot;user&quot;, &quot;password&quot;, &quot;database&quot;, 3306, null, MYSQLI_CLIENT_MULTI_STATEMENTS);<br>$mysqli-&gt;query(&quot;CREATE TABLE example (id INT PRIMARY KEY, name VARCHAR(255))&quot;);<br>$mysqli-&gt;query(&quot;INSERT INTO example VALUES (1, &#39;John&#39;)&quot;);<br>$mysqli-&gt;query(&quot;INSERT INTO example VALUES (2, &#39;Jane&#39;)&quot;);<br>$mysqli-&gt;query(&quot;INSERT INTO example VALUES (3, &#39;Jack&#39;)&quot;);<br><br>$mysqli-&gt;query(&quot;SET GLOBAL READ_ONLY=1&quot;);<br>$mysqli-&gt;query(&quot;FLUSH TABLES WITH READ LOCK&quot;);<br>$mysqli-&gt;query(&quot;UNLOCK TABLES&quot;);<br><br>$mysqli-&gt;query(&quot;INSERT INTO example VALUES (4, &#39;Sam&#39;)&quot;);<br><br>$mysqli-&gt;query(&quot;SET @replica = &#39;replica1&#39;&quot;);<br>$mysqli-&gt;query(&quot;SELECT * FROM example INTO OUTFILE &#39;/var/lib/mysql-files/example.csv&#39;&quot;);<br><br>$mysqli-&gt;refresh(MYSQLI_REFRESH_REPLICA, &quot;replica1&quot;);<br><br>$mysqli-&gt;close();</pre><p>In this example, we use the MYSQLI_REFRESH_REPLICA constant to refresh a single replica called replica1. This ensures that any changes made to the database are propagated to that replica.</p><p>This is a useful addition for those working with MySQL clusters who need more control over replica refreshing.</p><p><strong>Performance Improvements with Inheritance Cache</strong></p><p>PHP 8.1 includes a new inheritance cache that improves the performance of projects that use inheritance extensively. This cache avoids repeating expensive operations like searching and iterating over method and property tables.</p><p>The inheritance cache comes disabled by default, but you can enable it in your php.ini file:</p><pre>opcache.jit_buffer_size=100M<br>opcache.jit=tracing<br>opcache.jit_debug=0<br>opcache.jit_hot_func=1<br>opcache.inheritance_cache=1</pre><p>With these settings, PHP will start to cache the property and method table of a class the first time it’s loaded. This table is then reused for every subclass, avoiding the expensive operations of finding and iterating through the tables. As a result, you can expect a significant improvement in the performance of projects that use inheritance extensively.</p><p>Here’s an example that demonstrates how to use the inheritance cache:</p><pre>class Base {<br>    protected $a = 0;<br>    public function setA(int $a) {<br>        $this-&gt;a = $a;<br>    }<br>    public function getA() {<br>        return $this-&gt;a;<br>    }<br>}<br>class Sub extends Base {}<br><br>// Without inheritance cache<br>for ($i = 0; $i &lt; 1000000; $i++) {<br>    $sub = new Sub();<br>    $sub-&gt;setA($i);<br>}<br><br>// With inheritance cache<br>ini_set(&#39;opcache.inheritance_cache&#39;, &#39;1&#39;);<br>for ($i = 0; $i &lt; 1000000; $i++) {<br>    $sub = new Sub();<br>    $sub-&gt;setA($i);<br>}</pre><p>In this example, we define a Base class with a property and two methods. We then define a Sub class that extends Base. We create instances of the Sub class in a loop and set the value of the property in each instance. We run the loop twice, once without the inheritance cache enabled and once with it enabled.</p><p>Without the inheritance cache, the loop takes significantly longer to execute. With the inheritance cache enabled, the loop runs much faster, demonstrating the performance benefits of the inheritance cache.</p><p><strong>First-Class Callable Syntax</strong></p><p>In previous versions of PHP, calling a function or method required the use of the call_user_func or call_user_func_array functions, which can be cumbersome and less efficient. PHP 8.1 introduces first-class callable syntax, which allows you to call a callable directly using the following syntax:</p><pre>$callable = function($arg1, $arg2) {<br>    return $arg1 + $arg2;<br>};<br><br>$result = $callable(1, 2);<br>echo $result; // Output: 3</pre><p>In this example, the callable is defined as an anonymous function and assigned to the $callable variable. The callable is then called directly using the $callable(1, 2) syntax, resulting in a more efficient and readable code.</p><p>This feature can be especially useful when working with higher-order functions or functional programming paradigms. With first-class callable syntax, you can easily pass functions as arguments or return them from other functions.</p><p><strong>Conclusion</strong></p><p>PHP 8.1 brings many exciting new features and improvements to the language, including pure intersection types, enums, the never return type, fibers, new readonly properties, final class constants, and more. These features can help you write cleaner, more efficient, and more powerful code, and can make your applications more robust and reliable.</p><p>Whether you’re a seasoned PHP developer or just starting, PHP 8.1 has something to offer. So why not upgrade your application today and take advantage of these exciting new features?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddc40ce9bf7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>