<?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[Beyn Technology - Medium]]></title>
        <description><![CDATA[Articles are written by our teammates on the subjects we have experienced. - Medium]]></description>
        <link>https://medium.com/beyn-technology?source=rss----88fe3e34120f---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Beyn Technology - Medium</title>
            <link>https://medium.com/beyn-technology?source=rss----88fe3e34120f---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:09:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/beyn-technology" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Choosing Between DIY Approach vs. API Gateways: Finding the Right Balance for the API Management]]></title>
            <link>https://medium.com/beyn-technology/choosing-between-diy-approach-vs-api-gateways-finding-the-right-balance-for-the-api-management-d10adf7f7550?source=rss----88fe3e34120f---4</link>
            <guid isPermaLink="false">https://medium.com/p/d10adf7f7550</guid>
            <dc:creator><![CDATA[Mert Simsek]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 13:46:58 GMT</pubDate>
            <atom:updated>2024-03-28T13:46:58.076Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of API management, developers often face the dilemma of whether to leverage API gateways or implement certain functionalities within their application code. This decision carries implications for flexibility, performance, cost, and maintainability. In this blog post, we’ll explore the trade-offs between adopting API gateways and implementing DIY solutions within application code, helping you find the optimal approach for your API management needs. In today’s fast-paced world of software development, the management of APIs plays a critical role in ensuring the success and scalability of modern applications. At the heart of API management lie crucial decisions regarding how to handle various aspects of API traffic, security, and optimization. One of the fundamental decisions developers often grapple with is whether to rely on robust API gateway solutions or to craft bespoke implementations directly within their application code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*0gkLEgMpbk4Fa5ToiGEN_A.png" /><figcaption><a href="https://info.support.huawei.com/info-finder/encyclopedia/en/API+Gateway.html">https://info.support.huawei.com/info-finder/encyclopedia/en/API+Gateway.html</a></figcaption></figure><p>API gateways offer a comprehensive suite of features designed to streamline API management tasks. These include routing requests to appropriate backend services, implementing authentication and authorization mechanisms, enforcing rate-limiting policies, caching responses for improved performance, and transforming request and response payloads to meet specific requirements. By centralizing these functionalities within a dedicated gateway layer, developers can achieve greater consistency, scalability, and security across their APIs. On the other hand, opting for a do-it-yourself (DIY) approach involves implementing these functionalities directly within the application codebase. This approach offers developers unparalleled flexibility and control over the behavior of their APIs. By customizing each aspect of API management according to their specific needs, developers can fine-tune performance, integrate seamlessly with existing systems, and adapt rapidly to evolving requirements. However, the decision between API gateways and DIY solutions is not a binary one and entails careful consideration of various factors.</p><p>Let’s check out a rate limit code instance in Go. In this code example, we import the rate package from golang.org/x/time, which provides functionality for rate limiting. We create a rate limiter that allows up to 3 requests per second. Then, we send 5 requests sequentially and check if the limiter allows each request. If it does, we process the request; otherwise, we inform the user that the rate limit has been exceeded. So is it really worth doing this within the project?</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br><br> &quot;golang.org/x/time/rate&quot;<br>)<br><br>func main() {<br> // Create a rate limiter that accepts up to 3 requests per second<br> limiter := rate.NewLimiter(3, 1)<br><br> // Send 5 requests sequentially<br> for i := 0; i &lt; 5; i++ {<br>  // If the limiter allows the request, proceed<br>  if limiter.Allow() {<br>   fmt.Println(&quot;Request processed&quot;)<br>  } else {<br>   fmt.Println(&quot;Rate limit exceeded. Please try again later.&quot;)<br>  }<br>  time.Sleep(200 * time.Millisecond)<br> }<br>}</pre><p>There is another code instance in Go. It’s checking “api-key” which is common for API communication. we create an HTTP server that requires API keys to authenticate requests. The API keys are stored in a map, and each incoming request is checked against this map to ensure its validity. If the API key is valid, the request is processed; otherwise, an HTTP status code 401 Unauthorized is returned. The apiAuthMiddleware function serves as middleware to handle API key authentication before passing the request to the actual handler. Likewise, what does “api-key” control do in a player service or product service? At this point, we are also dealing with its testing processes and performance losses.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br>)<br><br>// Create a map to store API keys<br>var apiKeys = map[string]bool{<br> &quot;api-key-1&quot;: true,<br> &quot;api-key-2&quot;: true,<br>}<br><br>// HTTP middleware function to authenticate API keys<br>func apiAuthMiddleware(next http.Handler) http.Handler {<br> return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {<br>  apiKey := r.Header.Get(&quot;X-API-Key&quot;)<br><br>  // Check if the API key is valid<br>  if _, ok := apiKeys[apiKey]; !ok {<br>   http.Error(w, &quot;Unauthorized&quot;, http.StatusUnauthorized)<br>   return<br>  }<br><br>  next.ServeHTTP(w, r)<br> })<br>}<br><br>func main() {<br> // Create an HTTP handler using the API authentication middleware<br> http.Handle(&quot;/&quot;, apiAuthMiddleware(http.HandlerFunc(handler)))<br><br> // Start the server<br> fmt.Println(&quot;Server listening on :8080&quot;)<br> http.ListenAndServe(&quot;:8080&quot;, nil)<br>}<br><br>// Sample handler function<br>func handler(w http.ResponseWriter, r *http.Request) {<br> fmt.Fprintf(w, &quot;Hello, World!&quot;)<br>}</pre><p>Implementing rate limiting, API key authentication and so on abilities at the API gateway level offers several advantages over handling them within individual projects. Furthermore, handling rate limiting and authentication at the gateway enhances scalability. The gateway acts as a centralized point for managing incoming requests, allowing it to efficiently handle high volumes of traffic, distribute load evenly, and enforce access controls without overburdening individual services. This scalability ensures that the system can handle spikes in traffic and accommodate future growth seamlessly. Overall, leveraging the capabilities of the API gateway for rate limiting and API key authentication simplifies management, improves scalability, and ensures consistency, making it a preferred approach for modern API architectures.</p><p>We’ll delve deeper into the advantages and challenges of both approaches, exploring real-world examples and best practices to help you navigate this decision-making process effectively. Whether you’re building a small-scale application with tight budget constraints or architecting a large-scale microservices ecosystem, finding the right balance between convenience, performance, cost, and maintainability is essential for achieving long-term success in API management. Let’s dive in and uncover the insights that will empower you to make informed decisions tailored to your unique requirements and objectives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*YIYqE0CFAWAwzVctmlmQrw.png" /></figure><ol><li><strong>Routing:</strong> API Gateways can efficiently route incoming requests to the appropriate backend services based on predefined rules and paths.</li><li><strong>Authentication and Authorization:</strong> They facilitate secure access to APIs by implementing various authentication mechanisms such as OAuth, API keys, or JWT tokens. Additionally, they enforce access control policies to ensure that only authorized users or applications can access protected resources.</li><li><strong>Rate Limiting:</strong> API Gateways can enforce rate-limiting policies to prevent abuse or overloading of backend services by limiting the number of requests a client can make within a specified time frame.</li><li><strong>Caching:</strong> By caching responses from backend services, API Gateways can improve the performance and scalability of APIs by reducing the load on backend systems and minimizing response times for frequently accessed data.</li><li><strong>Request and Response Transformation:</strong> They can transform incoming requests or outgoing responses to comply with specific formats or standards, such as converting between different data formats (e.g., JSON to XML) or filtering sensitive information before sending responses to clients.</li><li><strong>Logging and Monitoring:</strong> API Gateways offer built-in logging and monitoring capabilities to track API usage, monitor performance metrics, and detect and troubleshoot errors or anomalies in real-time.</li><li><strong>Traffic Management:</strong> They enable traffic shaping and load balancing to distribute incoming requests evenly across multiple backend servers or microservices, ensuring high availability and scalability of APIs.</li><li><strong>Security:</strong> API Gateways provide features like SSL/TLS termination, request validation, and threat protection to enhance the security posture of APIs and protect against common security threats such as SQL injection or cross-site scripting (XSS).</li><li><strong>Versioning and Lifecycle Management:</strong> They facilitate API versioning and lifecycle management, allowing developers to introduce changes or updates to APIs seamlessly while ensuring backward compatibility and minimal disruption to existing clients.</li><li><strong>Integration with External Services:</strong> API Gateways can integrate with external services such as identity providers, logging platforms, or third-party API management tools to extend their functionality and streamline API management workflows.</li></ol><p>By leveraging these capabilities, API Gateways simplify and streamline the management of APIs, allowing developers to focus on building and delivering high-quality services without getting bogged down by cumbersome processes or infrastructure concerns. If developers choose to implement the functionalities typically provided by an API Gateway directly within their software project, several drawbacks and negative aspects may arise:</p><ol><li><strong>Increased Complexity:</strong> Incorporating routing, authentication, rate limiting, caching, request/response transformation, logging, monitoring, traffic management, security, versioning, and integration functionalities directly within the software project significantly increases its complexity. Developers must handle each of these aspects individually, leading to a more intricate and convoluted codebase.</li><li><strong>Higher Development and Maintenance Costs:</strong> Building and maintaining these functionalities within the software project require substantial development effort and ongoing maintenance. Developers need to allocate additional resources for implementing, testing, debugging, and updating each feature, resulting in higher development costs and longer time-to-market.</li><li><strong>Lack of Specialization and Best Practices:</strong> API Gateways are purpose-built tools designed specifically for managing API traffic and implementing common API management functionalities. By reinventing these functionalities within the software project, developers may overlook industry best practices, optimization techniques, and specialized features provided by dedicated API Gateway solutions.</li><li><strong>Scalability Challenges:</strong> Managing API traffic and ensuring scalability can be challenging without the infrastructure and optimizations provided by API Gateways. Handling increased traffic, distributing load across servers, and maintaining high availability become more complex and error-prone when implemented directly within the software project.</li><li><strong>Security Risks:</strong> Implementing security features such as authentication, authorization, and rate limiting without the expertise and built-in security measures of API Gateways may introduce security vulnerabilities and risks. Developers must ensure proper handling of sensitive data, protection against common security threats, and adherence to security best practices, which can be error-prone and time-consuming.</li><li><strong>Limited Flexibility and Extensibility:</strong> While developers have more control over the implementation of functionalities within their software project, this approach may limit flexibility and extensibility compared to using an API Gateway. Incorporating new features, integrating with external services, and adapting to changing requirements become more challenging and time-consuming without the modular and extensible architecture of API Gateways.</li><li><strong>Reduced Performance and Efficiency:</strong> Without the optimizations and performance enhancements provided by API Gateways, the software project may experience decreased performance and efficiency, particularly under high loads. Handling API traffic, managing caching, and optimizing response times require careful implementation and may not achieve the same level of performance as dedicated API Gateway solutions.</li></ol><p>While implementing API management functionalities within the software project offers increased control and customization, it also comes with significant drawbacks, including increased complexity, higher development and maintenance costs, scalability challenges, security risks, limited flexibility, and reduced performance. Developers should carefully weigh these factors and consider the trade-offs before deciding whether to build these functionalities in-house or leverage dedicated API Gateway solutions like Kong.</p><h3>Kong Gateway</h3><p><a href="https://konghq.com/products/kong-gateway">Kong Gateway</a> is a powerful tool that empowers developers to efficiently manage their APIs while providing various functionalities to streamline the API management process. With Kong, developers can easily set up routing rules to direct incoming requests to the appropriate backend services, ensuring efficient traffic distribution and load balancing. Additionally, Kong offers a wide range of authentication and authorization plugins, allowing developers to enforce security policies and control access to API endpoints effectively. Rate limiting capabilities in Kong enable developers to set usage limits for APIs, preventing abuse or overloading of backend systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*9srzZmYvVFP8-aefFXVHJA.png" /></figure><p>Furthermore, Kong’s caching functionality helps improve API performance by caching responses from backend services, reducing response times for frequently accessed data One of the key features of Kong is its extensibility through plugins. Developers can leverage various plugins available in the Kong ecosystem to customize and enhance the functionality of their API gateway. Whether it’s request and response transformation, logging and monitoring, or integration with external services, Kong provides a rich set of plugins to cater to diverse requirements.</p><p>Moreover, Kong’s robust security features, including ACL, JWT validation, and rate limiting, help protect APIs against common security threats and ensure data integrity and confidentiality. Overall, Kong API Gateway simplifies the complexities of API management, offering developers a scalable, flexible, and secure solution to efficiently manage their APIs and deliver high-quality services to their users.</p><p>For installation: <a href="https://github.com/Kong/kong">https://github.com/Kong/kong</a></p><ol><li>To start, clone the Docker repository and navigate to the compose folder.</li></ol><pre>git clone https://github.com/Kong/docker-kong<br>cd docker-kong/compose/</pre><ol><li>Start the Gateway stack using:</li></ol><pre>KONG_DATABASE=postgres docker-compose --profile database up</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpPiK5ImFnQISopZ6HkInw.png" /></figure><h4>Creating a service</h4><p>In Kong, creating a service involves defining an upstream service that represents the backend service or microservice to which incoming requests will be proxied. This process enables Kong to route incoming requests to the appropriate backend service based on predefined rules and configurations. Let’s break down the steps to create a service in Kong:</p><pre>curl -i -s -X POST http://localhost:8001/services \<br>  --data name=example_service \<br>  --data url=&#39;http://httpbin.org&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWhLadMfcGXy-PGbw5fvtA.png" /></figure><p>Once you’ve created a service within Kong Gateway, each service is assigned a distinct identifier, often referred to as its ID. This ID serves as a unique reference point for the service within Kong’s system. Alternatively, if you specified a name during the service creation process, you can also use that name to identify the service in subsequent interactions.</p><p>To access and inspect the current configuration and status of a service, you’ll utilize its designated service URL. This URL structure follows a consistent pattern: /services/{service name or ID}. By appending the specific name or ID of the service to the base /services endpoint, you construct the URL necessary to access detailed information about that particular service.</p><pre>curl -X GET http://localhost:8001/services/example_service</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-GRtzmHrCGiYoELF8EJUA.png" /></figure><h4>Creating a route</h4><p>Routes in Kong Gateway dictate the behavior of incoming requests, determining how they are proxied and directed within the gateway’s infrastructure. To associate a route with a particular service, you can create a new route by issuing a POST request to the designated service URL.</p><p>In the context of configuring a new route, let’s consider a practical example where we want to direct traffic to the example_service service that was previously created. Suppose we wish to configure a route for requests targeting the /mock path.</p><pre>curl -i -X POST http://localhost:8001/services/example_service/routes \<br> --data &#39;paths[]=/mock&#39; \<br> --data name=example_route</pre><p>Update and add a tag for previous route.</p><pre>curl --request PATCH \<br>  --url localhost:8001/services/example_service/routes/example_route \<br>  --data tags=&quot;tutorial&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHImo5gsMSODP853EIl-zg.png" /></figure><h4>Rate Limit</h4><p>The rate limiting plugin is installed by default on Kong Gateway, and can be enabled by sending a POST request to the <a href="https://docs.konghq.com/gateway/latest/admin-api/#add-plugin">plugins</a> object on the Admin API:</p><pre>curl -i -X POST http://localhost:8001/plugins \<br>  --data name=rate-limiting \<br>  --data config.minute=5 \<br>  --data config.policy=local</pre><p>Send 6 mock requests:</p><pre>for _ in {1..6}; do curl -s -i localhost:8000/mock/anything; echo; sleep 1; done<br></pre><p>I’ve seen this message after limit exceeded. Service-level and route-level might be activated.</p><p><a href="https://docs.konghq.com/gateway/latest/get-started/rate-limiting/">Service-Level Rate Limiting:</a> At the service level, rate limiting is applied globally to all routes associated with a particular service. This means that regardless of the specific endpoint or path being accessed within the service, the rate limit rules defined at the service level will be enforced uniformly. Service-level rate limiting is ideal for scenarios where consistent rate limiting policies need to be applied across multiple endpoints or when rate limiting is primarily based on the overall traffic volume directed towards a particular service.</p><p><a href="https://docs.konghq.com/gateway/latest/get-started/rate-limiting/">Route-Level Rate Limiting:</a> Conversely, route-level rate limiting allows administrators to define rate limit rules that are specific to individual routes or endpoints within a service. This granular approach enables fine-tuning of rate limiting policies based on the unique characteristics and requirements of each API endpoint. Route-level rate limiting is particularly useful when different endpoints within the same service may have distinct usage patterns or when certain endpoints require more restrictive rate limits compared to others.</p><p>By offering both service-level and route-level rate limiting capabilities, Kong Gateway empowers administrators to implement flexible and tailored rate limiting policies that suit the needs of their APIs and applications. Whether enforcing global rate limits across entire services or applying targeted rate limits to specific endpoints, Kong’s rate limiting plugin provides a comprehensive solution for controlling API traffic and ensuring optimal performance, reliability, and security.</p><p>{ “message”: “API rate limit exceeded” }</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*yxEvvEwswvLbCAKiYusaXQ.png" /></figure><h4>Proxy Caching</h4><p>Kong employs caching as a key strategy to enhance performance and optimize response times for API requests. By leveraging the Proxy Cache plugin, Kong accelerates performance by storing and serving cached responses, thereby reducing the need for repeated requests to upstream services.</p><p>The Proxy Cache plugin operates by caching responses based on various configurable criteria, including response codes, content types, and request methods. This allows Kong to intelligently cache responses that meet specific criteria, improving efficiency and reducing latency for subsequent requests.</p><pre>curl -i -X POST http://localhost:8001/plugins \<br> --data &quot;name=proxy-cache&quot; \<br> --data &quot;config.request_method=GET&quot; \<br> --data &quot;config.response_code=200&quot; \<br> --data &quot;config.content_type=application/json&quot; \<br> --data &quot;config.cache_ttl=30&quot; \<br> --data &quot;config.strategy=memory&quot;</pre><pre>curl -i -s -XGET http://localhost:8000/mock/anything | grep X-Cache</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5k94bz6KRDmrun39-9RWMQ.png" /></figure><p>From now on, our response will be served by in-memory cache. <br>The proxy caching plugin can be used in various scenarios to enhance the performance and scalability of API endpoints. Here are some common situations where the proxy caching plugin can be beneficial:</p><ol><li><strong>Frequent Read Operations:</strong> When API endpoints serve predominantly read operations and the response data doesn’t change frequently, proxy caching can significantly reduce response times by serving cached responses instead of hitting the backend server for every request.</li><li><strong>Static Content Delivery:</strong> If your API serves static content such as images, CSS files, or JavaScript files, proxy caching can cache these resources at the edge, reducing latency and offloading traffic from the backend servers.</li><li><strong>Reducing Server Load:</strong> By caching responses at the gateway level, proxy caching reduces the load on backend servers, allowing them to handle more requests and improving overall system performance and scalability.</li><li><strong>Handling Burst Traffic:</strong> In scenarios where there are sudden spikes in traffic, proxy caching can help absorb the increased load by serving cached responses, preventing backend servers from becoming overwhelmed.</li><li><strong>Improving User Experience:</strong> Caching frequently accessed data or resources closer to the user improves the user experience by reducing latency and response times, leading to faster page loads and smoother interactions with the application.</li><li><strong>API Rate Limiting:</strong> Proxy caching can be used in conjunction with rate limiting to cache responses for requests that exceed the rate limit, ensuring that even when rate limits are reached, users still receive responses without overwhelming the backend servers.</li><li><strong>Content Delivery Networks (CDNs):</strong> When integrating Kong with a CDN, proxy caching can be used to cache content at the CDN’s edge locations, further reducing latency and improving content delivery performance globally.</li></ol><h4>Enable authentication</h4><p>Authentication serves as the gatekeeper of access, ensuring that only authorized individuals or systems can interact with a resource. In the realm of API management, authentication takes center stage as API Gateway Authentication, acting as the guardian of data flow between clients and upstream services.</p><p>Within Kong Gateway’s extensive plugin ecosystem, you’ll find a diverse array of authentication methods tailored to meet various security needs. These methods encompass the most prevalent and trusted standards in the industry, ensuring robust protection for your APIs and services.</p><p>Among the common authentication mechanisms supported by Kong Gateway are:</p><ul><li>Key Authentication: A straightforward method where clients provide an API key for authentication, granting access based on the validity of the key.</li><li>Basic Authentication: A simple yet effective method where clients authenticate themselves using a username and password combination, which is then encoded and transmitted with each request.</li><li>OAuth 2.0 Authentication: A widely adopted standard for delegated authorization, allowing clients to obtain access tokens to interact with protected resources on behalf of a user.</li><li>LDAP Authentication: An advanced method that integrates with Lightweight Directory Access Protocol (LDAP) servers, enabling centralized authentication and user management across distributed systems.</li><li>OpenID Connect: A modern authentication protocol built on top of OAuth 2.0, providing identity layer capabilities and facilitating secure authentication and single sign-on (SSO) across applications and services.</li></ul><p>Create a new consumer</p><pre>curl -i -X POST http://localhost:8001/consumers/ \<br> --data username=luka</pre><p>Assign the consumer a key</p><pre>curl -i -X POST http://localhost:8001/consumers/luka/key-auth \<br> --data key=top-secret-key</pre><p>Global key</p><pre>curl -X POST http://localhost:8001/plugins/ \<br>   --data &quot;name=key-auth&quot;  \<br>   --data &quot;config.key_names=apikey&quot;</pre><p>Let’s see the result. We receive 401 status code until sending a valid key for this request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwxEqly7xKwu4FkFKMzFkg.png" /></figure><h3>To Sum Up</h3><p>In summary, Kong Gateway offers a robust solution for optimizing API performance, scalability, and reliability through its versatile proxy caching plugin. By leveraging caching at the gateway level, Kong enables organizations to significantly reduce response times, alleviate server load, and enhance the overall user experience. With the ability to cache frequently accessed data, handle burst traffic, and serve static content efficiently, Kong Gateway empowers businesses to deliver fast, reliable, and scalable API services to their users. Whether it’s accelerating read operations, improving content delivery, or integrating with CDNs, Kong’s proxy caching capabilities provide a comprehensive solution for optimizing API endpoints and ensuring seamless interactions with applications. Overall, Kong Gateway serves as a powerful tool for modernizing API infrastructure, driving innovation, and delivering exceptional digital experiences to users worldwide.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d10adf7f7550" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyn-technology/choosing-between-diy-approach-vs-api-gateways-finding-the-right-balance-for-the-api-management-d10adf7f7550">Choosing Between DIY Approach vs. API Gateways: Finding the Right Balance for the API Management</a> was originally published in <a href="https://medium.com/beyn-technology">Beyn Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 8 most common mistakes I encounter during a sprint]]></title>
            <link>https://medium.com/beyn-technology/the-8-most-common-mistakes-during-a-sprint-b0514298dbc8?source=rss----88fe3e34120f---4</link>
            <guid isPermaLink="false">https://medium.com/p/b0514298dbc8</guid>
            <category><![CDATA[mistakes-to-avoid]]></category>
            <category><![CDATA[mistakes]]></category>
            <category><![CDATA[sprint-goal]]></category>
            <category><![CDATA[sprint-planning]]></category>
            <category><![CDATA[sprint]]></category>
            <dc:creator><![CDATA[Goren Acay]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 11:36:13 GMT</pubDate>
            <atom:updated>2024-02-28T11:36:13.691Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*ve22gPagUee6TmcubWJOPQ.jpeg" /></figure><p>Scrum methodology offers a fast, flexible, and customer-focused approach to software development processes. However, errors occurring during sprints within this process can adversely affect project success. In this article, I will explain the problems I encountered during sprints and the solutions we found to these problems.</p><blockquote>The project is essentially divided into time blocks, and a product output is delivered after each time block, with the cycle repeating itself. These time frames in Scrum are referred to as “<strong>sprints</strong>” and can be planned for up to one month at most.</blockquote><p>Having sprints longer than a month contradicts the Scrum framework. It’s particularly important to limit risk and cost within a one-month period and to reduce the complexity of the work. During a sprint, project members select tasks from within product components and define subtasks to complete the selected tasks. These subtasks are referred to as “<strong>tasks</strong>.” Throughout the sprint, each project member takes on their respective task and strives to complete the tasks they’ve been assigned by the end of the sprint. As the project progresses, sprint evaluations are conducted at the end of each sprint, and a new sprint is created. Sprints are also monitored on a daily basis.</p><p>Summarizing the most common 8 errors during the sprint process(I will exemplify with the mistakes I have experienced):</p><p><strong>1 - Unclear Sprint Objectives: </strong>Failure to define clear objectives before the sprint begins can hinder the team’s focus and effective functioning throughout the sprint.</p><blockquote><strong>e.g.</strong> In a recent sprint, our overall goal was to “improve the user experience”. However, this goal was quite vague and did not provide clarity on what the team should focus on. As a result, team members were scattered in different directions and we were unable to make effective progress throughout the sprint. To resolve this situation, we improved the process by breaking down the objectives before the sprint started to make them more specific and measurable.</blockquote><p><strong>2 - Inadequate Sprint Planning:</strong> Incomplete understanding of requirements or unrealistic estimations during sprint planning can lead to unexpected issues during the sprint.</p><blockquote><strong>e.g.</strong> In the past, during a sprint planning meeting, we created a forward-looking plan before fully analyzing our requirements and realistically making our estimates. This led to unexpected problems during the sprint and difficulties in completing some tasks. We later corrected this mistake by investing more time in the planning process and analyzing the requirements in more depth.</blockquote><p><strong>3 - Lack of Measurable Criteria: </strong>Failure to establish clear measurable criteria for each sprint can make evaluating sprint results and measuring success challenging.</p><blockquote><strong>e.g.</strong> At the end of a sprint, we did not set clear measurable criteria to evaluate success and therefore could not fully understand what was or was not successful. This made it difficult to evaluate sprint results and continuously improve. We then started to set specific success criteria for each task and evaluated performance against these criteria at the end of the sprint.</blockquote><p><strong>4 - Handling Variable Requirements:</strong> Failing to plan for coping with unexpected requirement changes during the sprint can prevent the team from achieving sprint objectives.</p><blockquote><strong>e.g.</strong> During a sprint, there was an unexpected change in priority and our team was caught off guard. Without a plan to deal with this change, we struggled to achieve our sprint goals. After this experience, we created a mechanism to be flexible to unexpected changes and adjust our plans accordingly.</blockquote><p><strong>5 - External Interventions: </strong>External interventions or unexpected changes in priorities during the sprint can distract the team and reduce efficiency.</p><blockquote><strong>e.g.</strong> In the past, during a sprint, a senior manager wanted to add an unexpected feature, which distracted the team and disrupted our sprint plan. To deal with this type of interference, we set up a communication and decision-making process that would protect our team from external influences and keep them focused on our sprint goals.</blockquote><p><strong>6 - Insufficient Communication and Collaboration: </strong>Lack of adequate communication and collaboration among team members can prevent problem-solving and hinder reaching objectives throughout the sprint.</p><blockquote><strong>e.g.</strong> During a sprint, we failed to make progress on a specific task due to incompatibilities and lack of communication between team members. This made us realize that our collaboration was lacking and we needed to communicate with each other more often. We then solved this problem by organizing regular communication and collaboration meetings.</blockquote><p><strong>7 - Accumulation of Technical Debt:</strong> Prioritizing accumulating technical debt over quality work during the sprint may require additional time and resources in the future.</p><blockquote>e.g. In the past, we used some technical shortcuts to get quick results during the sprint and didn’t prioritize writing quality code. This resulted in the accumulation of technical debt, which required extra time and resources in the future. Later, we solved this problem by focusing more on code quality and reducing technical debt.</blockquote><p><strong>8 - Neglecting Retrospective and Feedback Meetings:</strong> Failure to hold or take seriously retrospective and feedback meetings at the end of the sprint can be a barrier to continuous improvement.</p><blockquote><strong>e.g. </strong>At the end of a sprint, we skipped the feedback meeting and missed the opportunity to evaluate our sprint process. This created a barrier to our continuous improvement. We then improved our process by regularly attending feedback meetings at the end of each sprint and improving our process based on the feedback received.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*vQtOIXkV2gH1vh9c7PjiiQ.jpeg" /></figure><blockquote>These mistakes I encountered can negatively affect project success when sprints are not managed effectively in the Scrum process. Therefore, it is very important to avoid these mistakes and strive for continuous improvement in Scrum practices.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0514298dbc8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyn-technology/the-8-most-common-mistakes-during-a-sprint-b0514298dbc8">The 8 most common mistakes I encounter during a sprint</a> was originally published in <a href="https://medium.com/beyn-technology">Beyn Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Runner Class in Cucumber]]></title>
            <link>https://medium.com/beyn-technology/how-to-use-runner-class-in-cucumber-40ba095aecd6?source=rss----88fe3e34120f---4</link>
            <guid isPermaLink="false">https://medium.com/p/40ba095aecd6</guid>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[cucumber]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Alper Yigit]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 11:52:49 GMT</pubDate>
            <atom:updated>2024-02-05T11:52:49.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4O2x2b2AcBakglqkKoovg.png" /></figure><p>Regular manual testing of the same test cases can waste time and money. It can also be boring for testers. We use test automation frameworks to make the same test scenarios run at regular intervals more efficient and save time and money. These frameworks develop over time and provide us with many conveniences. Today I will explain Runner Classes, an important feature of the Cucumber framework used with Selenium. First, I will briefly explain the runner classes and then I will write a sample automation code to show how it can be used in a real project. .</p><h4><strong>1. What is the Cucumber Framework ?</strong></h4><p>Cucumber is a BDD (Behavior Driven Development) tool that supports behavioral software development. BDD uses more understandable expressions to understand the software’s behavior and user scenarios. In this way, employees and business partners other than testers can clearly understand the purpose, scenarios and stages of the written automation.</p><p>The most important element that increases the understandability of automation written in Cucumber is the writing of test scenarios in Gherkin expressions. Scenarios are written in “feature” files in Gherkin format.</p><p>You can run your project from “feature” file. But this situation is not healthy in many ways. It would be better to use “Runner” classes to specify run conditions and apply filters to our test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lnqG02L7xzpCjeK6x29uWw.png" /><figcaption>A feature file sample</figcaption></figure><h4>2. Using The Runner Class in a Real Project</h4><p>Runner classes are classes that allow us to develop our project, choose which scenarios to run, and create test reports.</p><p>These parameters should be written inside the <a href="http://twitter.com/CucumberOptions">@CucumberOptions</a> notation.</p><p>I created a simple automation project on hepsiburada.com. I will not explain classes other than the Runner class because they are out of scope in this article. But I will add the github link of my project to end of the article. You can see the other classes and structure of the project.</p><p>Runner class of the project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e32c976ed48ff2eed85cac9cab9fee7/href">https://medium.com/media/5e32c976ed48ff2eed85cac9cab9fee7/href</a></iframe><h4>2.1 Plugin</h4><p>A path is given to this parameter. In this way, the test report of the run test is created and saved to the path we specified with the name we specified. Thanks to this parameter, we do not need to make an extra setup to report our test result.</p><pre>plugin = &quot;html:target/reports.html&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZkZi3iJumYJdpJk28Z6Mww.png" /></figure><p>As seen in the screenshot above, a report file was created in target file after the test is over. Report path can be changed from runner class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwZ4qt2xzNAZiFNYGhzQrQ.png" /><figcaption>This report can be opened as shown in the image above.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itbGwGN4Tx6zXmHk-InvrA.png" /><figcaption>View of the report</figcaption></figure><h4>2.2 Features</h4><p>We write the paths of the features we want to run in our project here.</p><pre>features = &quot;src/test/resources/features&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVrJaKxuqMbaZUMv2rIVbA.png" /></figure><h4>2.3 Glue</h4><p>Thanks to this parameter, we specify which class the codes of the test scenario we will run are under.</p><pre>glue = &quot;stepdefinitions&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TAoKL78PFG82FcAOAEinHg.png" /></figure><p>Since the codes of the test scenario we will run are in the stepdefinitions file, we wrote stepdefinitions to this parameter.</p><h4>2.4 dryRun</h4><p>As you know, in cucumber we first write the test steps and then write the codes of these steps. With the dryRun parameter, we determine whether test steps whose codes have not been written yet will be run. It can take 2 values. Default value of the parameter is “false”. When the value of the parameter is “false”, all scenarios are run, including the steps whose codes are not written. While the value of the parameter is “true”, if there are test steps for which code methods have not been created, the test will not be started. An error message will be returned indicating that there are test steps whose methods have not been written yet and how these methods should be written.</p><p>Let’s examine these two conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cIHyYnaEXByi49-O9dfiNw.png" /></figure><p>Created a new feature file. As you see, methods of some steps are missing.</p><pre>dryRun = false</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_HsdMEB-0Vj56WNv6ThwQ.png" /></figure><p>When the project was run with the dryRun parameter set to false, the last scenario we added was skipped and other scenarios were run. An error message was returned stating that these scenarios do not have code methods and how these methods can be created.</p><pre>dryRun = true</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4uhU9MLS4dbof5cZMD_oIg.png" /></figure><p>When the dryRun parameter was set to true, no scenario was run because there were missing code methods in one of the scenarios and an error was returned directly. You can understand from the running times that the other scenarios are not run.</p><h4>2.5 Tags</h4><p>We may not always want to run all test cases. This is the parameter where we specify which test cases we will run. For example: If we write <a href="http://twitter.com/smoke">@smoke</a> on one or more scenarios and write <a href="http://twitter.com/smoke">@smoke</a> in front of the “tags” parameter, only scenarios with the <a href="http://twitter.com/smoke">@smoke</a> tag will be run.</p><p>Let’s add some tags to our scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*1di97ltZ1SmbE_O30YzoYQ.png" /><figcaption>@login, @smoke and @regression tags added to negative login scenario.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*reoAW90vLyG_hDHgq4n9BQ.png" /><figcaption>@register, @smoke and @regression tags added to register scenario.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*Rzg4E8M9OhV3aSgxuCxhmw.png" /><figcaption>@search and @regression tags added to search product scenario.</figcaption></figure><p>Now, let’s examine some cases where the tags parameter does not have a value and where it does.</p><pre>tags = &quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48LKO6WcHO9sl_YLpwO50Q.png" /><figcaption>When the tags parameter has no value, all scenarios are run as seen in the image above.</figcaption></figure><pre>tags = &quot;@login&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t1gocSHL2P3EfSiXFLVjaQ.png" /><figcaption>Since the only scenario that has the <a href="http://twitter.com/login">@login</a> tag is the negative login scenario, only this scenario was run.</figcaption></figure><pre>tags = &quot;@search or @login&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTNFGnSVE8S9qKqs6gLWpQ.png" /><figcaption>Scenarios that have <a href="http://twitter.com/search">@search</a> or <a href="http://twitter.com/login">@login</a> tags were run</figcaption></figure><pre>tags = &quot;@login and @smoke&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6XCICpTyP8A32I-DEviPw.png" /><figcaption>Scenarios that have both <a href="http://twitter.com/login">@login</a> and <a href="http://twitter.com/smoke">@smoke</a> tags are run</figcaption></figure><pre>tags = &quot;@regression&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BDoAXHiLh4ZG6_P8JMbz1w.png" /><figcaption>Since all scenarios have the <a href="http://twitter.com/regression">@regression</a> tag, they are all run</figcaption></figure><pre>tags = &quot;@regression and not @login&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkwzRbYb5VoBFNCGrX5LWA.png" /><figcaption>Scenarios that have the <a href="http://twitter.com/regression">@regression</a> tag but not the <a href="http://twitter.com/login">@login</a> tag are run. That’s why login scenario was not run</figcaption></figure><h4>3. Summary</h4><p>In a test automation project using the Cucumber framework, tests can be run without using the Runner class, but using the Runner class gives us great advantages. We can easily report using the Runner class and specify where we want the report to be saved and only run the tests we want to run. Especially if you have a large automation project, using the Runner class is a must.</p><blockquote><em>That’s All</em></blockquote><p>Thank you for reading my article. I hope it will help you. If you have a question or advice, you can contact me via my e-mail address below.</p><p><a href="https://github.com/ialpery/Runner-Class-Article-For-Medium">GitHub - ialpery/Runner-Class-Article-For-Medium</a></p><p>İbrahim Alper Yiğit, QA Test Engineer</p><p>ialper.yigit@gmail.com</p><p><a href="https://github.com/ialpery">Github</a> | <a href="https://www.linkedin.com/in/ialperyigit/">Linkedin</a></p><h4><strong><em>References</em></strong></h4><ul><li><a href="https://cucumber.io/docs/cucumber/api/?lang=java">Cucumber Reference</a></li><li><a href="https://github.com/cucumber/cucumber-expressions#readme">GitHub - cucumber/cucumber-expressions: Human friendly alternative to Regular Expressions</a></li><li><a href="https://stackoverflow.com/">Newest Questions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40ba095aecd6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyn-technology/how-to-use-runner-class-in-cucumber-40ba095aecd6">How to Use Runner Class in Cucumber</a> was originally published in <a href="https://medium.com/beyn-technology">Beyn Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wars of Symfony Runtimes: A Performance Odyssey]]></title>
            <link>https://medium.com/beyn-technology/wars-of-symfony-runtimes-a-performance-odyssey-7b0120e8f9e1?source=rss----88fe3e34120f---4</link>
            <guid isPermaLink="false">https://medium.com/p/7b0120e8f9e1</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[swoole]]></category>
            <category><![CDATA[roadrunner]]></category>
            <category><![CDATA[frankenphp]]></category>
            <dc:creator><![CDATA[Emre Çalışkan]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 13:48:55 GMT</pubDate>
            <atom:updated>2024-02-01T13:48:55.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Pe1HGqJGgVyBH01OjvNkKw.png" /></figure><p>In the ever-evolving landscape of web application development, complexities arise as new technologies emerge daily. This rapid transformation provides developers with a plethora of options, but it also introduces challenges in making the right choices. Symfony, being a flexible and powerful PHP web application framework, offers developers a wide array of runtime options. However, making the correct choice among these options is crucial for the performance, scalability, and maintenance ease of an application. In this article, we will delve into a comparative analysis of Symfony’s different runtimes, exploring the advantages, disadvantages, and use-case scenarios for each. Choosing the right runtime for your Symfony applications can be a decisive factor in the success of your project.</p><p>This article aims to conduct a comprehensive comparison of notable Symfony runtimes, namely Swoole, Open Swoole, Road Runner, and FrankenPHP. By delving into the strengths, weaknesses, and optimal use cases of each runtime, we aim to guide developers in making informed decisions for their Symfony projects. The careful selection of a runtime can significantly influence the success of a Symfony application, and understanding the nuances of these alternatives is pivotal for developers navigating the ever-expanding landscape of web development.</p><h3>Runtime Selection Criteria</h3><blockquote>Certainly, when choosing a runtime, performance is undoubtedly a crucial factor, but it’s not solely dependent on performance. Other significant factors include:</blockquote><ol><li><strong>Developer Experience:</strong> Runtime selection impacts the developer experience. Developers can work more effectively when using a runtime that aligns well with their preferences. Factors such as user-friendly monitoring tools, debugging capabilities, and documentation significantly affect the developer experience.</li><li><strong>Community and Ecosystem Support:</strong> The presence of a strong community and a broad ecosystem behind a runtime provides developers with easier access to resources and faster issue resolution. Community-supported runtimes may have advantages in terms of adding new features and providing security updates.</li><li><strong>Project Requirements:</strong> The specific features and requirements of a project can be determinative in choosing the appropriate runtime. For example, certain runtimes might integrate better with specific databases or other external systems.</li><li><strong>Scalability and Resource Usage:</strong> The size and scale of a project can influence the choice of an appropriate runtime. Lightweight and scalable runtimes might be advantageous for smaller projects, while more robust runtimes that effectively manage resource usage may be preferred for larger-scale applications.</li><li><strong>Compatibility with Existing Infrastructure:</strong> Compatibility with other tools, services, and infrastructure elements used in the project can influence runtime selection. It’s essential for a runtime to be compatible with existing infrastructure and facilitate easy integration.</li><li><strong>Security and Update Policies:</strong> The runtime should adhere to security standards and receive regular updates to ensure the project’s long-term security.</li></ol><p>These factors, in addition to performance, play a crucial role in guiding the selection of an ideal runtime. Evaluating these considerations in a balanced manner can enhance the overall success and sustainability of a project.</p><p>Now that we have considered essential criteria such as developer experience, community support, documentation, security, and compatibility, it is pivotal to delve deeper into the performance aspects of the identified Symfony runtimes. Conducting a comprehensive performance analysis involves scrutinizing key metrics like Request per Second (RPS), latency values, and transfer speeds across different scenarios. By closely examining how each runtime handles these performance indicators, we can gain insights into their efficiency under various workloads. This deeper performance evaluation will guide us in making an informed decision, ensuring that not only do the chosen runtimes meet the project’s non-functional requirements but also deliver optimal speed and responsiveness crucial for a successful Symfony application.</p><h3>Test Endpoints</h3><p>These endpoints represent three distinct API routes in your Symfony application, each serving a different purpose:</p><ol><li><strong>Health Check Endpoint (</strong><strong>/health-check):</strong> This endpoint is used to assess the overall health of the application. When called, it performs a health check, evaluating the status of targeted services, and returns an HTTP 204 No Content response. This signifies that the core functionality of the application is active, and the health status is positive.</li><li><strong>Static Information Endpoint (</strong><strong>/static):</strong> This endpoint provides static information about the application by returning a simple JSON response. The JSON response typically includes constant values, versions, or other static details about the application. This endpoint offers quick and easy access for clients to gather basic information about the application.</li><li><strong>HTTP Requests Endpoint (</strong><strong>/http-request):</strong> This endpoint utilizes Symfony&#39;s Http service to send an HTTP GET request to another API (in this case, &quot;<a href="https://github.com/traefik/whoami">http://whoami/api</a>&quot;). The received response demonstrates the ability of the Symfony application to interact with external resources. This functionality can be utilized in scenarios such as fetching data from external APIs or accessing resources.<br><em>The </em><a href="https://github.com/traefik/whoami"><em>traefik/whoami</em></a><em> package is a simple example application that, upon receiving an HTTP request, provides detailed information about the source of the request. This application delivers an informative response containing HTTP headers, client IP address, request timestamp, and other relevant details.</em></li></ol><p>These three endpoints represent different usage scenarios, allowing for various tests to evaluate the overall performance of the application.</p><pre>&lt;?php<br><br>namespace App\Controller;<br><br>use App\Services\HttpService;<br>use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;<br>use Symfony\Component\HttpFoundation\JsonResponse;<br>use Symfony\Component\HttpFoundation\Response;<br>use Symfony\Component\Routing\Annotation\Route;<br><br>#[Route(&#39;/api&#39;, name: &#39;app_api_&#39;)]<br>class ApiController extends AbstractController<br>{<br>    #[Route(&#39;/health-check&#39;, name: &#39;health_check&#39;)]<br>    public function healthCheck(): Response<br>    {<br>        return new Response(&#39;&#39;, 204);<br>    }<br>    <br>    #[Route(&#39;/static&#39;, name: &#39;static&#39;)]<br>    public function static(): JsonResponse<br>    {<br>        return $this-&gt;json([<br>            &#39;status&#39; =&gt; true,<br>        ]);<br>    }<br><br>    #[Route(&#39;/http-request&#39;, name: &#39;http_request&#39;)]<br>    public function httpRequest(HttpService $httpService): JsonResponse<br>    {<br>        return $this-&gt;json(json_decode($httpService-&gt;get(&#39;http://whoami/api&#39;)));<br>    }<br>}</pre><h3>Docker Images</h3><h3>Open Swoole</h3><pre>FROM php:8.3-alpine<br><br>COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/<br>COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer<br><br>RUN install-php-extensions pcntl sockets openswoole<br><br>COPY . /var/www<br><br>WORKDIR /var/www<br><br>RUN composer install --no-dev<br><br>ENV APP_RUNTIME=&quot;Runtime\Swoole\Runtime&quot;<br><br>ENTRYPOINT [&quot;php&quot;, &quot;public/index.php&quot;]</pre><h3>Swoole</h3><pre>FROM php:8.3-alpine<br><br>COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/<br>COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer<br><br>RUN install-php-extensions pcntl sockets swoole<br><br>COPY . /var/www<br><br>WORKDIR /var/www<br><br>RUN composer install --no-dev<br><br>ENV APP_RUNTIME=&quot;Runtime\Swoole\Runtime&quot;<br><br>ENTRYPOINT [&quot;php&quot;, &quot;public/index.php&quot;]</pre><h3>RoadRunner</h3><pre>FROM php:8.3-alpine<br><br>COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/<br>COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer<br>COPY --from=ghcr.io/roadrunner-server/roadrunner:latest /usr/bin/rr /usr/local/bin/rr<br><br>RUN install-php-extensions pcntl sockets<br><br>COPY . /var/www<br><br>WORKDIR /var/www<br><br>RUN composer install --no-dev<br><br>ENV APP_RUNTIME=&quot;Runtime\RoadRunnerSymfonyNyholm\Runtime&quot;<br><br>ENTRYPOINT [&quot;rr&quot;, &quot;serve&quot;]</pre><h3>FrankenPHP</h3><pre>FROM php:8.3-alpine<br><br>COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/<br>COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer<br><br>RUN install-php-extensions pcntl sockets<br><br>COPY . /var/www<br><br>WORKDIR /var/www<br><br>RUN apk add jq<br><br>RUN wget -O/usr/local/bin/frankenphp $(wget -O- https://api.github.com/repos/dunglas/frankenphp/releases/latest | jq &#39;.assets[] | select(.name==&quot;frankenphp-linux-x86_64&quot;) | .browser_download_url&#39; -r) &amp;&amp; chmod +x /usr/local/bin/frankenphp<br><br>RUN composer install --no-dev<br><br>ENV APP_RUNTIME=&quot;Runtime\FrankenPhpSymfony\Runtime&quot;<br>ENV APP_PUBLIC_PATH=&quot;/var/www/public&quot;<br>ENV MAX_REQUESTS=&quot;500&quot;<br>ENV REQUEST_MAX_EXECUTION_TIME=&quot;500&quot;<br>ENV CADDY_SERVER_ADMIN_PORT=&quot;3823&quot;<br>ENV CADDY_SERVER_LOG_LEVEL=&quot;WARN&quot;<br>ENV CADDY_SERVER_LOGGER=&quot;json&quot;<br>ENV CADDY_SERVER_SERVER_NAME=&quot;http://:9804&quot;<br>ENV CADDY_SERVER_WORKER_COUNT=&quot;16&quot;<br>ENV CADDY_SERVER_EXTRA_DIRECTIVES=&quot;&quot;<br><br>ENTRYPOINT [&quot;frankenphp&quot;,&quot;run&quot;, &quot;-cCaddyfile&quot;]</pre><h3>Docker Compose</h3><pre>version: &quot;3.9&quot;<br><br>services:<br>    whoami:<br>        container_name: &quot;whoami&quot;<br>        image: &quot;containous/whoami&quot;<br>    openswoole:<br>        container_name: &quot;openswoole&quot;<br>        image: &quot;ghcr.io/thecaliskan/symfony-benchmark:openswoole&quot;<br>        ports:<br>            - &quot;9801:9801&quot;<br>    swoole:<br>        container_name: &quot;swoole&quot;<br>        image: &quot;ghcr.io/thecaliskan/symfony-benchmark:swoole&quot;<br>        ports:<br>            - &quot;9802:9802&quot;<br>    roadrunner:<br>        container_name: &quot;roadrunner&quot;<br>        image: &quot;ghcr.io/thecaliskan/symfony-benchmark:roadrunner&quot;<br>        ports:<br>            - &quot;9803:9803&quot;<br>    frankenphp:<br>        container_name: &quot;frankenphp&quot;<br>        image: &quot;ghcr.io/thecaliskan/symfony-benchmark:frankenphp&quot;<br>        ports:<br>            - &quot;9804:9804&quot;</pre><p><a href="https://github.com/thecaliskan/symfony-benchmark">GitHub - thecaliskan/symfony-benchmark: Symfony Benchmark Example Project for Symfony Runtime Servers</a></p><h3>Install</h3><p>To perform benchmark tests on your server, follow these steps to set up the application:</p><pre>wget https://raw.githubusercontent.com/thecaliskan/symfony-benchmark/master/docker-compose.yml<br><br>docker compose up -d</pre><h3>Benchmark</h3><p>Now that your Symfony application is up and running, you can conduct benchmark tests for various server options. Use the following commands for each server:</p><h3>OpenSwoole</h3><pre>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9801/api/health-check<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9801/api/static<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9801/api/http-request</pre><h3>Swoole</h3><pre>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9802/api/health-check<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9802/api/static<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9802/api/http-request</pre><h3>RoadRunner</h3><pre>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9803/api/health-check<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9803/api/static<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9803/api/http-request</pre><h3>FrankenPHP</h3><pre>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9804/api/health-check<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9804/api/static<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9804/api/http-request</pre><h3>Stack</h3><h3>Software</h3><p><strong>PHP:</strong> v8.3.1 <br><strong>Symfony:</strong> v7.0.2<br><strong>Open Swoole:</strong> v22.1.2<br><strong>Swoole:</strong> v5.1.1<br><strong>RoadRunner:</strong> v2023.3.8<br><strong>FrankenPHP:</strong> v1.0.3<br><strong>Docker Engine:</strong> v24.0.7<br><strong>Operating System:</strong> Fedora Linux 39 (Workstation Edition)<br><strong>Kernel Version:</strong> Linux 6.6.8–200.fc39.x86_64</p><h3>Hardware</h3><p>Intel i9 9900K (8 Core/16 Thread, 3.6 Ghz, Turbo 5.0 Ghz)<br>32 GB DDR4 3200 Mhz<br>Samsung 970 EvoPlus SSD (3.500w/3.300r MB/s)</p><h3>Test Results</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FMM2rV%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FMM2rV%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FMM2rV%2Fplain-s.png%3Fv%3D1&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="512" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebfb4d4f28bace81bbe52de3383da9cb/href">https://medium.com/media/ebfb4d4f28bace81bbe52de3383da9cb/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FKFAWx%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FKFAWx%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FKFAWx%2Fplain-s.png%3Fv%3D1&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="512" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4b4bb46e7201d89d938a81d8e867b88/href">https://medium.com/media/e4b4bb46e7201d89d938a81d8e867b88/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2F6DsYz%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2F6DsYz%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2F6DsYz%2Fplain-s.png%3Fv%3D1&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="512" frameborder="0" scrolling="no"><a href="https://medium.com/media/d22f89129aa0d40b67e4f5bad2e7d918/href">https://medium.com/media/d22f89129aa0d40b67e4f5bad2e7d918/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fw7f5J%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fw7f5J%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fw7f5J%2Fplain-s.png%3Fv%3D1&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="805" frameborder="0" scrolling="no"><a href="https://medium.com/media/8963f45c1a8a64b5dd0691a4e07d83f5/href">https://medium.com/media/8963f45c1a8a64b5dd0691a4e07d83f5/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FOs6DR%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FOs6DR%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FOs6DR%2Fplain-s.png%3Fv%3D1&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="805" frameborder="0" scrolling="no"><a href="https://medium.com/media/8691b1fe25984d9c8f79633808cacc1d/href">https://medium.com/media/8691b1fe25984d9c8f79633808cacc1d/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fqi1Xy%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fqi1Xy%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fqi1Xy%2Fplain-s.png%3Fv%3D1&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="805" frameborder="0" scrolling="no"><a href="https://medium.com/media/449e179603e45f60f974993ead2a75d7/href">https://medium.com/media/449e179603e45f60f974993ead2a75d7/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2F7MMaQ%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2F7MMaQ%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2F7MMaQ%2Fplain-s.png%3Fv%3D1&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/690803913d01d4545a0f001e551a2e7d/href">https://medium.com/media/690803913d01d4545a0f001e551a2e7d/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2F5eha7%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2F5eha7%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2F5eha7%2Fplain-s.png%3Fv%3D1&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/37e6b9eaa4ec8dc790d0dc11fa62121a/href">https://medium.com/media/37e6b9eaa4ec8dc790d0dc11fa62121a/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FwFugT%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FwFugT%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FwFugT%2Fplain-s.png%3Fv%3D1&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/102c5eb235516720d31da6702a14cb8b/href">https://medium.com/media/102c5eb235516720d31da6702a14cb8b/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FxDHzY%2F2%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FxDHzY%2F2%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FxDHzY%2Fplain-s.png%3Fv%3D2&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/df6f5cdac5807db6e0d7b85ccac1f579/href">https://medium.com/media/df6f5cdac5807db6e0d7b85ccac1f579/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FwmaBT%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FwmaBT%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FwmaBT%2Fplain-s.png%3Fv%3D1&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbe1aaef5913e37c077b146f486406ea/href">https://medium.com/media/fbe1aaef5913e37c077b146f486406ea/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FoXsJZ%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FoXsJZ%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FoXsJZ%2Fplain-s.png%3Fv%3D1&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/272c89a897bd23561e15697a3fc786a8/href">https://medium.com/media/272c89a897bd23561e15697a3fc786a8/href</a></iframe><h3>Conclusion</h3><p>The benchmark tests evaluating the performance of Symfony Framework reveal a distinct advantage of OpenSwoole and Swoole runtimes compared to others. This is particularly evident in “Health Check,” “Static,” and “Http Request” scenarios, where low latency values and high Request Per Second rates are prominent.</p><p>The superiority of OpenSwoole and Swoole in these aspects is a significant advantage for ensuring applications run quickly and efficiently. These runtimes effectively respond to user requests with low latency values and successfully handle high request loads with their high RPS rates.</p><p>Developers should focus on optimizing RoadRunner and FrankenPHP based on these benchmark results. Doing so will contribute to improving the performance of Symfony projects overall, positively impacting user experience and fostering a more efficient application development process.</p><p>When it comes to selecting the runtime environment for Symfony projects, what are the key factors that influence your decision? Which runtime do you prefer for your projects, and how do considerations such as performance, developer experience, or specific project requirements play a role in your choice? Please share your own preferences and the reasons you take into account when making these decisions.</p><blockquote>Thank you for reading!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b0120e8f9e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyn-technology/wars-of-symfony-runtimes-a-performance-odyssey-7b0120e8f9e1">Wars of Symfony Runtimes: A Performance Odyssey</a> was originally published in <a href="https://medium.com/beyn-technology">Beyn Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hola FrankenPHP! Laravel Octane Servers Comparison: Pushing the Boundaries of Performance]]></title>
            <link>https://medium.com/beyn-technology/hola-frankenphp-laravel-octane-servers-comparison-pushing-the-boundaries-of-performance-d3e7ad8e652c?source=rss----88fe3e34120f---4</link>
            <guid isPermaLink="false">https://medium.com/p/d3e7ad8e652c</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[swoole]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[roadrunner]]></category>
            <category><![CDATA[frankenphp]]></category>
            <dc:creator><![CDATA[Emre Çalışkan]]></dc:creator>
            <pubDate>Wed, 03 Jan 2024 08:33:06 GMT</pubDate>
            <atom:updated>2024-01-07T22:07:48.110Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p008sU7Sb8gjBUjq" /><figcaption>Photo by <a href="https://unsplash.com/@larskienle?utm_source=medium&amp;utm_medium=referral">Lars Kienle</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As the complexity of web applications continues to grow, developers are increasingly focusing on performance and scalability. Laravel, known as a powerful PHP framework, addresses these needs. However, various solutions are being developed to further enhance the performance and scalability of this framework.</p><p>Laravel Octane is one such solution, designed to make Laravel applications faster and more scalable. However, there are significant differences in the types of servers Octane uses to achieve these goals. Used mostly on three servers so far with Laravel Octane. Open Swoole, Swoole and RoadRunner</p><p>In an unexpected turn, a new participant has joined the array of Octane servers: FrankenPHP. This new server is crafted to push the boundaries of performance even further, offering an optimized solution for Laravel applications. In this article, we’ll evaluate FrankenPHP alongside the traditional servers, Open Swoole, Swoole and RoadRunner, comparing the innovations and performance features each brings to the table.</p><p>For Laravel developers, this article will provide an in-depth analysis performance and resource consumption of Octane servers, helping them understand which server option may be more effective in specific scenarios. By exploring the advantages of Open Swoole, Swoole and RoadRunner and introducing FrankenPHP, we aim to guide you in selecting the most suitable server to maximize your Laravel applications. Are you ready for an exciting journey into the universe of Octane servers, now featuring this new contender?</p><h3>Test Endpoints</h3><p>These endpoints represent three distinct API routes in your Laravel application, each serving a different purpose:</p><ol><li><strong>Health Check Endpoint (</strong><strong>/health-check):</strong> This endpoint is used to assess the overall health of the application. When called, it performs a health check, evaluating the status of targeted services, and returns an HTTP 204 No Content response. This signifies that the core functionality of the application is active, and the health status is positive.</li><li><strong>Static Information Endpoint (</strong><strong>/static):</strong> This endpoint provides static information about the application by returning a simple JSON response. The JSON response typically includes constant values, versions, or other static details about the application. This endpoint offers quick and easy access for clients to gather basic information about the application.</li><li><strong>HTTP Requests Endpoint (</strong><strong>/http-request):</strong> This endpoint utilizes Laravel&#39;s Http service to send an HTTP GET request to another API (in this case, &quot;<a href="https://github.com/traefik/whoami">http://whoami/api</a>&quot;). The received response demonstrates the ability of the Laravel application to interact with external resources. This functionality can be utilized in scenarios such as fetching data from external APIs or accessing resources.<br><em>The </em><a href="https://github.com/traefik/whoami"><em>traefik/whoami</em></a><em> package is a simple example application that, upon receiving an HTTP request, provides detailed information about the source of the request. This application delivers an informative response containing HTTP headers, client IP address, request timestamp, and other relevant details.</em></li></ol><p>These three endpoints represent different usage scenarios, allowing for various tests to evaluate the overall performance of the application.</p><pre>&lt;?php<br><br>use App\Services\HttpService;<br>use Illuminate\Http\Request;<br>use Illuminate\Support\Facades\Response;<br>use Illuminate\Support\Facades\Route;<br><br>/*<br>|--------------------------------------------------------------------------<br>| API Routes<br>|--------------------------------------------------------------------------<br>|<br>| Here is where you can register API routes for your application. These<br>| routes are loaded by the RouteServiceProvider and all of them will<br>| be assigned to the &quot;api&quot; middleware group. Make something great!<br>|<br>*/<br><br>Route::get(&#39;/health-check&#39;, fn (Request $request) =&gt; Response::noContent())-&gt;name(&#39;health-check&#39;);<br>Route::get(&#39;/static&#39;, fn (Request $request) =&gt; Response::json([&#39;status&#39; =&gt; true]))-&gt;name(&#39;static&#39;);<br>Route::get(&#39;/http-request&#39;, fn (Request $request, HttpService $httpService) =&gt; Response::json(json_decode($httpService-&gt;get(&#39;http://whoami/api&#39;))))-&gt;name(&#39;http-request&#39;);</pre><h3>Docker Images</h3><h4>Open Swoole</h4><pre>FROM php:8.3-alpine<br><br>COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/<br>COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer<br><br>RUN install-php-extensions pcntl sockets openswoole<br><br>COPY . /var/www<br>COPY .env.example /var/www/.env<br><br>WORKDIR /var/www<br><br>RUN composer install --no-dev<br><br>ENTRYPOINT [&quot;php&quot;, &quot;artisan&quot;, &quot;octane:start&quot;, &quot;--server=swoole&quot;, &quot;--port=9801&quot;, &quot;--workers=16&quot;, &quot;--host=0.0.0.0&quot;]</pre><h4>Swoole</h4><pre>FROM php:8.3-alpine<br><br>COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/<br>COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer<br><br>RUN install-php-extensions pcntl sockets swoole<br><br>COPY . /var/www<br>COPY .env.example /var/www/.env<br><br>WORKDIR /var/www<br><br>RUN composer install --no-dev<br><br>ENTRYPOINT [&quot;php&quot;, &quot;artisan&quot;, &quot;octane:start&quot;, &quot;--server=swoole&quot;, &quot;--port=9802&quot;, &quot;--workers=16&quot;, &quot;--host=0.0.0.0&quot;]</pre><h4>RoadRunner</h4><pre>FROM php:8.3-alpine<br><br>COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/<br>COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer<br>COPY --from=ghcr.io/roadrunner-server/roadrunner:latest /usr/bin/rr /usr/local/bin/rr<br><br>RUN install-php-extensions pcntl sockets<br><br>COPY . /var/www<br>COPY .env.example /var/www/.env<br><br>WORKDIR /var/www<br><br>RUN composer install --no-dev<br><br>ENTRYPOINT [&quot;php&quot;, &quot;artisan&quot;, &quot;octane:start&quot;, &quot;--server=roadrunner&quot;, &quot;--port=9803&quot;, &quot;--workers=16&quot;, &quot;--host=0.0.0.0&quot;]</pre><h4>FrankenPHP</h4><pre>FROM php:8.3-alpine<br><br>COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/<br>COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer<br><br>RUN install-php-extensions pcntl sockets<br><br>COPY . /var/www<br>COPY .env.example /var/www/.env<br><br>WORKDIR /var/www<br><br>RUN apk add jq<br><br>RUN wget -O/usr/local/bin/frankenphp $(wget -O- https://api.github.com/repos/dunglas/frankenphp/releases/latest | jq &#39;.assets[] | select(.name==&quot;frankenphp-linux-x86_64&quot;) | .browser_download_url&#39; -r) &amp;&amp; chmod +x /usr/local/bin/frankenphp<br><br>RUN composer install --no-dev<br><br>ENTRYPOINT [&quot;php&quot;, &quot;artisan&quot;, &quot;octane:start&quot;, &quot;--server=frankenphp&quot;, &quot;--port=9804&quot;, &quot;--workers=16&quot;, &quot;--host=0.0.0.0&quot;]</pre><h3>Docker Compose</h3><pre>version: &quot;3.9&quot;<br><br>services:<br>    whoami:<br>        container_name: &quot;whoami&quot;<br>        image: &quot;containous/whoami&quot;<br>    openswoole:<br>        container_name: &quot;openswoole&quot;<br>        image: &quot;ghcr.io/thecaliskan/laravel-benchmark:openswoole&quot;<br>        ports:<br>            - &quot;9801:9801&quot;<br>    swoole:<br>        container_name: &quot;swoole&quot;<br>        image: &quot;ghcr.io/thecaliskan/laravel-benchmark:swoole&quot;<br>        ports:<br>            - &quot;9802:9802&quot;<br>    roadrunner:<br>        container_name: &quot;roadrunner&quot;<br>        image: &quot;ghcr.io/thecaliskan/laravel-benchmark:roadrunner&quot;<br>        ports:<br>            - &quot;9803:9803&quot;<br>    frankenphp:<br>        container_name: &quot;frankenphp&quot;<br>        image: &quot;ghcr.io/thecaliskan/laravel-benchmark:frankenphp&quot;<br>        ports:<br>            - &quot;9804:9804&quot;</pre><p><a href="https://github.com/thecaliskan/laravel-benchmark">GitHub - thecaliskan/laravel-benchmark: Laravel Benchmark Example Project for Laravel Octane Servers</a></p><h3>Install</h3><p>To perform benchmark tests on your server, follow these steps to set up the application:</p><pre>wget https://raw.githubusercontent.com/thecaliskan/laravel-benchmark/master/docker-compose.yml<br><br>docker compose up -d</pre><h3>Benchmark</h3><p>Now that your Laravel application is up and running, you can conduct benchmark tests for various server options. Use the following commands for each server:</p><h4>OpenSwoole</h4><pre>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9801/api/health-check<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9801/api/static<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9801/api/http-request</pre><h4>Swoole</h4><pre>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9802/api/health-check<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9802/api/static<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9802/api/http-request</pre><h4>RoadRunner</h4><pre>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9803/api/health-check<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9803/api/static<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9803/api/http-request</pre><h4>FrankenPHP</h4><pre>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9804/api/health-check<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9804/api/static<br>wrk -t16 -c100 -d30s --latency  http://127.0.0.1:9804/api/http-request</pre><h3>Stack</h3><h4>Software</h4><p><strong>PHP:</strong> v8.3.1 <br><strong>Laravel:</strong> v10.39.0<br><strong>Laravel Octane:</strong> v2.2.6<br><strong>Open Swoole:</strong> v22.1.2<br><strong>Swoole:</strong> v5.1.1<br><strong>RoadRunner:</strong> v2023.3.8<br><strong>FrankenPHP:</strong> v1.0.3<br><strong>Docker Engine:</strong> v24.0.7<br><strong>Operating System:</strong> Fedora Linux 39 (Workstation Edition)<br><strong>Kernel Version:</strong> Linux 6.6.8–200.fc39.x86_64</p><h4>Hardware</h4><p>Intel i9 9900K (8 Core/16 Thread, 3.6 Ghz, Turbo 5.0 Ghz)<br>32 GB DDR4 3200 Mhz<br>Samsung 970 EvoPlus SSD (3.500w/3.300r MB/s)</p><h3>Test Results</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FpCTMx%2F9%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FpCTMx%2F9%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FpCTMx%2Fplain-s.png%3Fv%3D9&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="512" frameborder="0" scrolling="no"><a href="https://medium.com/media/27320bf50f791b5c4f490e701710ace1/href">https://medium.com/media/27320bf50f791b5c4f490e701710ace1/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fs3JMM%2F11%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fs3JMM%2F11%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fs3JMM%2Fplain-s.png%3Fv%3D11&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="512" frameborder="0" scrolling="no"><a href="https://medium.com/media/663b9a342b863b12a5747a3c04ffedec/href">https://medium.com/media/663b9a342b863b12a5747a3c04ffedec/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FJwMxM%2F11%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FJwMxM%2F11%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FJwMxM%2Fplain-s.png%3Fv%3D11&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="512" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b9bac70657a130c75fcb94a6d89bc74/href">https://medium.com/media/5b9bac70657a130c75fcb94a6d89bc74/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FgKj0V%2F7%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FgKj0V%2F7%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FgKj0V%2Fplain-s.png%3Fv%3D7&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="805" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c9ff48fa7c1edbf8d7987524a03967f/href">https://medium.com/media/6c9ff48fa7c1edbf8d7987524a03967f/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fs7MlT%2F4%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fs7MlT%2F4%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fs7MlT%2Fplain-s.png%3Fv%3D4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="805" frameborder="0" scrolling="no"><a href="https://medium.com/media/e46af93b1249d09ab615d507296372c8/href">https://medium.com/media/e46af93b1249d09ab615d507296372c8/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fo6sPV%2F4%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fo6sPV%2F4%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fo6sPV%2Fplain-s.png%3Fv%3D4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="805" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c2d992ba8304ffa55e7d89fe4124bf0/href">https://medium.com/media/4c2d992ba8304ffa55e7d89fe4124bf0/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2F9uXId%2F4%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2F9uXId%2F4%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2F9uXId%2Fplain-s.png%3Fv%3D4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/73b802b15e6e278e6e36cc9e2be4e7c3/href">https://medium.com/media/73b802b15e6e278e6e36cc9e2be4e7c3/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fb5vvR%2F4%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fb5vvR%2F4%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fb5vvR%2Fplain-s.png%3Fv%3D4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a9e36392ab77b1c1b520509136c9620/href">https://medium.com/media/7a9e36392ab77b1c1b520509136c9620/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2F0nZ5T%2F2%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2F0nZ5T%2F2%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2F0nZ5T%2Fplain-s.png%3Fv%3D2&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbc7f8d244f5f2afc8784295f26ccfa8/href">https://medium.com/media/bbc7f8d244f5f2afc8784295f26ccfa8/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2F0Z7L9%2F4%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2F0Z7L9%2F4%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2F0Z7L9%2Fplain-s.png%3Fv%3D4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a02ebc7a0ff09cc75d352929070bfcf/href">https://medium.com/media/4a02ebc7a0ff09cc75d352929070bfcf/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FM5CI6%2F5%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FM5CI6%2F5%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FM5CI6%2Fplain-s.png%3Fv%3D5&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ed8ac78eace50e6d635c3f721dae7a8/href">https://medium.com/media/4ed8ac78eace50e6d635c3f721dae7a8/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2F7QDhF%2F2%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2F7QDhF%2F2%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2F7QDhF%2Fplain-s.png%3Fv%3D2&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/b970a50e975bcdf4e56a3b4536904072/href">https://medium.com/media/b970a50e975bcdf4e56a3b4536904072/href</a></iframe><h3>Conclusion</h3><p>In this article, we delved into different server options used for Laravel Octane: Open Swoole, Swoole, RoadRunner, and the newcomer, FrankenPHP. The comparisons included benchmark tests to measure their performances.</p><p>Based on the test outcomes, you can choose the server that best fits the needs of your project. Tests conducted through health checks, static information, and HTTP requests helped identify the standout features of each server.</p><p>It’s crucial to note that since each application has unique requirements and features, careful consideration should be given to selecting the right server to achieve optimal performance. This article aims to provide Laravel Octane users and performance enthusiasts with a guide to making the most effective server choice for their projects.</p><blockquote>Thank you for reading!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3e7ad8e652c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyn-technology/hola-frankenphp-laravel-octane-servers-comparison-pushing-the-boundaries-of-performance-d3e7ad8e652c">Hola FrankenPHP! Laravel Octane Servers Comparison: Pushing the Boundaries of Performance</a> was originally published in <a href="https://medium.com/beyn-technology">Beyn Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collaborated APIs in Kong Insomnia: Fostering Team Productivity]]></title>
            <link>https://medium.com/beyn-technology/collaborated-apis-in-kong-insomnia-fostering-team-productivity-88a5d45b2284?source=rss----88fe3e34120f---4</link>
            <guid isPermaLink="false">https://medium.com/p/88a5d45b2284</guid>
            <dc:creator><![CDATA[Mert Simsek]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 08:14:55 GMT</pubDate>
            <atom:updated>2023-12-22T08:14:55.070Z</atom:updated>
            <content:encoded><![CDATA[<p>Kong Insomnia is a powerful tool designed to streamline and enhance the API development and management process. As an integral part of the Kong API platform, Insomnia provides developers with robust features for designing, testing, and debugging APIs. With a user-friendly interface, Insomnia offers an intuitive environment for crafting requests, viewing responses, and collaborating on API development projects. Its versatility makes it an invaluable asset for beginners and experienced developers, ensuring a seamless API development experience.</p><p>With Insomnia you can:</p><ul><li><strong>Debug APIs</strong> using the most popular protocols and formats.</li><li><strong>Design APIs</strong> using the native OpenAPI editor and visual preview.</li><li><strong>Test APIs</strong> using native test suites.</li><li><strong>Mock APIs</strong> <em>will be coming soon.</em></li><li><strong>Build CI/CD pipelines</strong> using the native Insomnia CLI for linting and testing.</li><li><strong>Collaborate with others</strong> using the many collaboration features to share your projects.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fbPEYM5JvapEfetj7_x9Tw.png" /></figure><p><a href="https://insomnia.rest/">The Collaborative API Development Platform</a></p><p>For the application to be installed, the link below will be the starting point for its operating system.</p><p><a href="https://docs.insomnia.rest/insomnia/install">https://docs.insomnia.rest/insomnia/install</a></p><p><strong>API Design:</strong></p><ul><li><em>Efficiency and Consistency:</em> Kong Insomnia provides a user-friendly interface for designing APIs, ensuring that developers can efficiently create API specifications and maintain consistency across projects.</li><li><em>Collaboration:</em> With built-in features, team members can seamlessly work together on API design, fostering a collaborative and iterative design process.</li></ul><p><strong>API Testing:</strong></p><ul><li><em>Comprehensive Testing:</em> Insomnia allows developers to conduct comprehensive testing of APIs, including unit tests, integration tests, and load tests, ensuring the reliability and functionality of the APIs.</li><li><em>Automation Support:</em> The platform supports automation, enabling developers to automate the testing process and integrate it into their continuous integration/continuous deployment (CI/CD) pipelines.</li></ul><p><strong>API Debugging:</strong></p><ul><li><em>Real-time Debugging:</em> Developers can debug APIs in real-time, identify issues promptly, and make necessary adjustments, streamlining the debugging process.</li><li><em>Interactive Debugging:</em> Insomnia offers interactive debugging tools, allowing developers to interact with APIs during the debugging phase and gain insights into their behavior.</li></ul><p><strong>API Documentation:</strong></p><ul><li><em>Automatic Documentation:</em> Kong Insomnia automatically generates documentation based on the API design, reducing the manual effort required for documentation creation.</li><li><em>Readability and Accessibility:</em> The generated documentation is well-structured, enhancing readability, and it is easily accessible for both developers and API consumers.</li></ul><h3>Spec, Collection, Tests</h3><p>Let’s take a quick look at what we have in the application. We are currently in the <strong>SPEC </strong>section, where we define API-related specifications. As you can see in the picture, there are “<strong>SPEC</strong>”, “<strong>COLLECTION</strong>”, “<strong>TESTS</strong>” sections and we will use each of them together to enrich and strengthen the API. The Specs section serves as a central hub for creating detailed API documentation. Developers can provide clear descriptions for each endpoint, specify the expected data format, and document any required authentication methods. This documentation not only aids developers working on the project but also becomes a valuable resource for external developers or team members interacting with the API.</p><p>I found the <strong>Swagger Petstore</strong> file online and imported it into the Insomnia tool. On the right, we see the preview area of the yaml file. Insomnia instantly displays errors and warnings in the interface. For example, if some fields are missing or their types are wrong, I fix them immediately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S79q6IaijTUmPGb0iZ72DA.png" /></figure><p>After fixing the errors here, let’s meet a great feature; “<strong>Generate Collection</strong>”. From the specifications and documents we have created, we can instantly execute our requests with the HTTP client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHSQEVC9FQV9nK6T5QSO6A.png" /></figure><p>Now we see our automatically created list where we can make HTTP requests. Whatever we just wrote in the Swagger specification, we can run it live here. The “Collections” section in Insomnia is a powerful feature that streamlines the organization and execution of API requests. It serves as a container for grouping related requests, making it easier for developers to manage and test different API endpoints within a project. Collections allow developers to categorize and organize API requests based on their functionality or purpose. This hierarchical structure enhances project clarity, providing a logical order to the various API calls required for a specific task. Collections can be exported and shared among team members, promoting collaboration and consistency across the development team. This feature is especially valuable when working on projects with distributed teams or when transitioning between different development environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yg-tzs3T_CIeYJDdWot_6A.png" /></figure><p>Collections support using environment variables, enabling developers to parameterize requests and create dynamic workflows. This flexibility is particularly useful when working with different environments, such as development, staging, and production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PGDui6P1EYaX9jD9eMA8TA.png" /></figure><p>Now let’s look at the <strong>TESTS </strong>section. It is a critical component for ensuring the reliability of APIs through automated testing. This section allows developers to define and execute test scenarios for API requests, validating that the responses meet expected criteria and ensuring consistent functionality. In the Tests section, developers can define various scenarios to validate the correctness of API responses. This includes assertions to check response status codes, response body content, headers, and other relevant parameters. By articulating specific test cases, developers ensure that the API behaves as intended under different conditions. Tests in Insomnia can be automated to run with each API request, providing immediate feedback on the health of the API. Automation helps catch issues early in the development process, preventing potential problems from progressing to later stages. Insomnia allows the integration of tests into continuous integration workflows, enabling developers to incorporate API testing seamlessly into their CI/CD pipelines. This ensures that tests are executed consistently and that API changes are thoroughly validated before deployment. Developers can use the Tests section not only for response validation but also for performance testing. By defining benchmarks and measuring response times, developers gain insights into the API’s performance under various conditions, helping identify and address potential bottlenecks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6nQqf8YjToQNg_TrKIxxQ.png" /></figure><p>Another test case is where I added scenarios such as whether the returned response content is an object or an array or whether it contains an “id” value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*136sIQGiavuW0ZVzvYEv7g.png" /></figure><h4>Collaboration with Git</h4><p>Insomnia’s integrated Git support is a powerful tool for enhancing collaboration among teams and managing API development processes more effectively. This feature allows storing all documentation and configuration of API projects in a Git repository. Team members can utilize Insomnia’s Git integration to review the project’s history, track changes, and revert to previous versions when necessary. Moreover, it facilitates seamless integration of changes between different team members, making concurrent work more organized and conflict-free. Insomnia’s Git integration empowers teams to manage their API development projects more efficiently, providing developers with a significant advantage in understanding project history and collaborating effectively. Consequently, transparency and cohesion in project processes contribute to team members working more productively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VWhaNN8KG2rjY2infqbaw.png" /></figure><blockquote><strong>Note</strong>: Sync with Git applies to users subscribed to <a href="https://insomnia.rest/pricing">Team plan</a> and above, refer to <a href="https://insomnia.rest/pricing">pricing</a>.</blockquote><p><a href="https://docs.insomnia.rest/insomnia/git-sync">Sync with Git</a></p><h4>Kong for Kubernetes</h4><p><em>Kong for Kubernetes</em> integration in Insomnia leverages the powerful capabilities of Kong, an open-source API gateway, within Kubernetes environments. This integration allows developers to seamlessly manage and secure their APIs by combining the flexibility of Kong with the orchestration capabilities of Kubernetes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXL1Md7u_MkX5IrFCGrNlQ.png" /></figure><p><em>Kong,</em> known for its robust features like load balancing, authentication, rate limiting, and more, can be seamlessly deployed in Kubernetes clusters. Insomnia provides a dedicated set of features and configurations to interact with Kong for Kubernetes, making it easier for developers to set up and manage Kong instances within their Kubernetes infrastructure.</p><h3>To Sum Up</h3><p>Insomnia has become more than just a powerful tool for API developers; it has become a key element in accelerating your workflow and managing API projects more effectively. With its user-friendly interface, comprehensive API documentation, and testing and debugging features, Insomnia saves developers time and helps detect errors in the early stages of development. Furthermore, its robust collection and testing capabilities enhance collaboration among teams, ensuring projects progress in a more organized and reliable manner. If you aim to develop and manage APIs effectively, using Insomnia is inevitable. Catering to a wide audience, from beginners to expert users, this tool provides an environment that makes your API development process more efficient and enjoyable. It’s time to say “hello” to faster, more reliable, and more user-friendly API projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88a5d45b2284" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyn-technology/collaborated-apis-in-kong-insomnia-fostering-team-productivity-88a5d45b2284">Collaborated APIs in Kong Insomnia: Fostering Team Productivity</a> was originally published in <a href="https://medium.com/beyn-technology">Beyn Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pytest: Use Console values with “conftest.py”]]></title>
            <link>https://medium.com/beyn-technology/pytest-use-console-values-with-conftest-py-5284615b73f6?source=rss----88fe3e34120f---4</link>
            <guid isPermaLink="false">https://medium.com/p/5284615b73f6</guid>
            <category><![CDATA[contests]]></category>
            <category><![CDATA[selenium-test-automation]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[pytest]]></category>
            <dc:creator><![CDATA[Murat Feyzioğlu]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 13:34:34 GMT</pubDate>
            <atom:updated>2023-11-29T13:34:34.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*5zx4ZlOvRqXRxrwg.png" /></figure><p>In the realm of software testing having an efficient testing suite is crucial to ensure the quality of your software applications. Pytest, an used testing framework, in the Python ecosystem has established itself as a reliable tool for creating and running tests. However, within Pytest there is a treasure called the conftest.py file. It is an asset that is often overlooked but can significantly transform your approach to test automation.</p><p>Whether you are a Quality Assurance Test Engineer, developer, or anyone involved in the testing process understanding and harnessing the potential of conftest.py can greatly enhance your testing workflow. This document aims to demystify the conftest.py file by exploring its capabilities and demonstrating how it can be leveraged to optimize your testing suite.</p><p>Together we will embark on a journey through the world of conftest.py. We will unravel its mysteries. Showcase its applications. From configuration management to fixture generation from customizing fixture behavior to integrating with third-party plugins and automating testing, in your CI/CD pipeline — conftest.py offers versatility that becomes invaluable once you comprehend its true potential. It can become your trusted ally in pursuit of top-notch software quality.<br>Whether you have been using Pytest for a while or are new, to the world of software testing this guide is here to help you make the most out of conftest.py. So let’s jump in and explore how we can utilize this tool to improve our testing efforts.</p><h3>How to Create and Use?</h3><p>Select or create a Directory. You should place your “conftest.py” file in the corresponding field of the test classes you intend to use. The “conftest.py” file applies to all test files within its own subdirectories. I choose “testCases” directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*fMwDG4t8UZFimCg-YnIzmw.png" /></figure><p>Inside the conftest.py file, you can define fixtures using the @pytest.fixture decorator. For example:</p><pre>import pytest<br><br>@pytest.fixture<br>def my_fixture():<br>    # Fixture setup code here<br>    yield<br>    # Fixture teardown code here (optional)</pre><p>This example defines a fixture named my_fixture. You can include setup and teardown code as needed within the fixture. You can also include other configurations or settings in the conftest.py file. For example, you are setting global test parameters, configuring logging, or defining hooks.</p><p>I want to show you an example. You can use this example exactly. In the example, there will be configuring logging, and defining hooks. This code gives that you can choose your explorer with your parameter afteryou can change as regarding your project.</p><pre>import pytest<br><br>from selenium import webdriver<br>from selenium.webdriver.chrome.service import Service as ChromeService<br><br><br>@pytest.fixture()<br>def setup(browser):<br>    if browser == &quot;firefox&quot;:<br>        driver = webdriver.Firefox()<br>        print(&quot;Launching Chrome browser&quot;)<br>        return driver<br>    elif browser == &quot;edge&quot;:<br>        driver = webdriver.Edge()<br>        print(&quot;Launching Firefox browser&quot;)<br>        return driver<br># if the user doesn&#39;t give any parameter.<br>    else:<br><br>        CHROMEDRIVER_PATH = &#39;C:/Users/Name/Desktop/chromedriver-win64/chromedriver.exe&#39;<br>        service = ChromeService(executable_path=CHROMEDRIVER_PATH)<br>        options = webdriver.ChromeOptions()<br>        driver = webdriver.Chrome(service=service, options=options)<br>        return driver<br><br># hooks, terminal info,<br># get the value from CLI/hooks<br>def pytest_addoption(parser):<br>    parser.addoption(&quot;--browser&quot;)<br><br># return the Browser value to setup method<br>@pytest.fixture()<br>def browser(request):<br>    return request.config.getoption(&quot;--browser&quot;)</pre><p>I added some comment lines for these functions but i would to explain some important parts.</p><pre>def pytest_addoption(parser):<br>    parser.addoption(&quot;--browser&quot;)</pre><p><strong>pytest_addoptions(parser):</strong></p><p>When you use this method, you can add an option on your console line. The pytest sees the “ — browser” option and it waits for a parameter after this.</p><p>— browser chrome</p><p>— browser edge etc.</p><pre>@pytest.fixture()<br>def browser(request):<br>    return request.config.getoption(&quot;--browser&quot;)</pre><p><strong>browser(request):</strong></p><p>This method takes your option from the console and returns.</p><p>chrome, edge, etc.</p><p>The main method is “<em>def setup(browser)</em>”. You need to define your fixture to your test method. As you see the method waits a parameter “browser”. browser(request) method gives the option to this parameter.</p><pre>def test_login(self, setup):</pre><p>Now you can use driver on your test method. There is a simple example. You will see there is no difference from the normal way to use “driver”. (<em>My chrome driver is a little bit different. That’s why i am using some different libraries and third party plugins</em>. )</p><pre>    def test_login(self, setup):<br>        self.driver = setup<br><br>        self.driver.get(self.baseURL)<br><br>        self.login_page = LoginPage(self.driver)<br>        print(self.driver)<br><br>        self.login_page.setUserName(self.username)<br>        print(self.driver)<br>        self.login_page.setPassword(self.password)<br>        self.login_page.clickLogin()<br>        act_title = self.driver.title<br><br>        if act_title == &quot;Dashboard / nopCommerce administration&quot;:<br>            assert True<br>        else:<br>            assert False<br><br>        self.driver.close()</pre><p>You can give a parameter from the console before the test run. And your driver is preparedaccording your parameter.</p><p>“pytest -v -s testCases/test_login.py <strong>— browser chrome</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*xA4MAVKcv9otrLoRriMrng.png" /></figure><p>First example, take a parameter from the console. It was a great feature. Now I want to show you how that add information to the console. It will be more useful if you use this feature.</p><p>For example, we have many engineers, project modules, etc and we want to separate or cluster. You can add information with “conftest.py”. These informations are readable from third-party pluggins. This is the biggest differences from the logs.</p><p>We are going to add this information with key and value.</p><pre>def pytest_configure(config):<br>    config._metadata[&#39;Project Name&#39;] = &#39;nop Commerce&#39;<br>    config._metadata[&#39;Module Name&#39;] = &#39;Customers&#39;<br>    config._metadata[&#39;Tester&#39;] = &#39;Murat_test&#39;</pre><p>when the conftest.py is worked, this method will be triggered. You can add what you want below your console lines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*BHjzzozjwtgjauUrwTG-Dw.png" /></figure><p>I hope these two exapmles will improve your automation. You will add information to the console and you will take parameters from the console. Don’t underestimatethe power of using a console. Your outputs and inputs will become more professional.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5284615b73f6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyn-technology/pytest-use-console-values-with-conftest-py-5284615b73f6">Pytest: Use Console values with “conftest.py”</a> was originally published in <a href="https://medium.com/beyn-technology">Beyn Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TCP Connection Practices in PHP Applications]]></title>
            <link>https://medium.com/beyn-technology/tcp-connection-practices-in-php-applications-14bef4bf2164?source=rss----88fe3e34120f---4</link>
            <guid isPermaLink="false">https://medium.com/p/14bef4bf2164</guid>
            <dc:creator><![CDATA[Mert Simsek]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 13:32:53 GMT</pubDate>
            <atom:updated>2023-11-04T13:32:53.616Z</atom:updated>
            <content:encoded><![CDATA[<p>I/O operations are indispensable for modern software. In this document, we will answer questions such as how we can optimize network I/O operation and what we should pay attention to. If we give an example of Network I/O operations; We can think of HTTP requests to an external web service, a database connection, or connections to external system services such as Redis, Elasticsearch, or message queuing systems. In particular, our applications exchange data through TCP connections, and we will see in which cases and how these connections are created or closed. As we said in the title, we will see these specifically in PHP runtime.</p><blockquote>Since there are many resources on the internet about topics such as <a href="https://www.guru99.com/difference-tcp-ip-vs-osi-model.html">TCP/IP vs OSI Model</a>, <a href="https://www.geeksforgeeks.org/tcp-3-way-handshake-process/">TCP 3-Way Handshake Process</a>, <a href="https://www.avast.com/c-tcp-vs-udp-difference">TCP vs UDP</a>, I continue by assuming that you know these topics.</blockquote><h4>TCP Connection States</h4><p>TCP connection states refer to states that represent their different phases. These states show how the connection between two points of communication is managed and when it goes through which stages. These states show the lifecycle of the TCP connection and indicate where the connection is at each stage. These states are important for network debugging and network traffic monitoring.</p><ul><li><strong>ESTABLISHED:</strong> This represents the situation where the TCP connection between two devices is successfully established and data transmission occurs. Communicating devices can exchange data.</li><li><strong>CLOSE-WAIT:</strong> This represents a phase where the local device sends data and the remote device waits for the connection to be closed. In other words, the local device made a shutdown request after sending the data and is now waiting for the other party to respond to the shutdown request.</li><li><strong>TIME-WAIT:</strong> This represents a phase in which the connection is waited for a period of time after being closed. The purpose of this wait is to make sure that the last packets from the connection are still being transmitted. During this time, no new connection can be established.</li><li><strong>LISTEN:</strong> Represents the state where a server application waits for incoming connections. The server listens on a specific port and accepts incoming connections.</li><li><strong>SYN-SENT:</strong> This represents the stage where the local device sends a SYN packet to initiate a connection. The other party is expected to respond to this SYN packet with SYN-ACK.</li><li><strong>SYN-RECEIVED:</strong> This represents the stage where the local device sends a SYN packet and the other party responds with SYN-ACK. Now the local device must complete the connection by sending an ACK packet.</li><li><strong>CLOSED:</strong> Represents the stage where the connection is completely closed and cannot be used for communication. This can happen before the connection is initiated or after it is closed.</li></ul><h4>HTTP Requests in PHP</h4><p>What happens when making HTTP requests in PHP applications? In the example below, a total of 20 requests are made to a remote machine using <strong>curl_multi_init</strong> and <strong>curl_multi_add_handle</strong>. As an HTTP verb, the POST method is used.</p><pre>&lt;?php<br>try {<br>    $url = &#39;http://server_web_container/bet&#39;;<br><br>    $data = [<br>        &#39;action&#39; =&gt; &#39;bet&#39;,<br>        &#39;amount&#39; =&gt; 0.10<br>    ];<br><br>    $totalRequests = 20;<br><br>    $mh = curl_multi_init();<br>    $ch = [];<br><br>    for ($i = 0; $i &lt; $totalRequests; $i++) {<br>        $ch[$i] = curl_init($url);<br>        curl_setopt($ch[$i], CURLOPT_POST, 1);<br>        curl_setopt($ch[$i], CURLOPT_POSTFIELDS, http_build_query($data));<br>        curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, true);<br>        curl_multi_add_handle($mh, $ch[$i]);<br>    }<br><br>    do {<br>        curl_multi_exec($mh, $running);<br>    } while ($running &gt; 0);<br><br>    for ($i = 0; $i &lt; $totalRequests; $i++) {<br>        curl_multi_remove_handle($mh, $ch[$i]);<br>        curl_close($ch[$i]);<br>    }<br><br>    curl_multi_close($mh);<br><br>    echo &quot;$totalRequests requests are handled totally.&quot;;<br>} catch (\Exception $e) {<br>    echo $e-&gt;getMessage();<br>}</pre><p>Since <strong>HTTP/1.1</strong> is used by default, we have another invisible line in the code as follows.</p><pre>curl_setopt($ch[$i], CURLOPT_HTTPHEADER, [&quot;Connection: keep-alive&quot;]);</pre><blockquote>Since the same options are available in Guzzle, Symfony or Laravel HTTP clients, there is no need to show examples of all of them one by one, so we are proceeding specifically with curl. You can see how you can add the same options in the relevant clients’ documentation.</blockquote><p>Connections between a client and server using <strong>HTTP/1.1</strong> automatically operate in keep-alive mode. In this way, we prevent connections from closing completely after data exchange, and we prevent new connections from being opened when we make a request to the same machine again because this costs time and resources. It saves time and resources because it prevents the process of establishing new connections. Rather than establishing a separate connection for each request, reusing the same connection is faster and uses server resources more efficiently.</p><blockquote>Additionally, when making a request as a client, we can add timeout and max header values and thus tell the other party how many seconds this TCP connection will remain alive or the maximum number of times it can be in this period, but determining the “keep-alive” time is usually a configuration setting on the server side and is not a direct response. It is not recommended to add it as an HTTP request header. However, some servers may allow clients to set the duration and number of “keep-alive” using request headers. Therefore, it is not always safe to use these values because the other party may not take these values into account.</blockquote><p>After the application is run, 20 TCP connections are opened and their status is <strong>ESTABLISHED</strong>. Currently, data is being exchanged between our local machine and the remote server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCoAHiuJaab1e-kHyvX4Dw.png" /></figure><p>When the relevant data exchange is completed on the local machine and 60 seconds have passed (depending on the configuration, but generally 60 seconds), we see that the status of the connections changes to <strong>CLOSE-WAIT</strong>. We now have the answers from the remote machine. If a request is made to the same <strong>IP:PORT</strong> address, curl will use these connections automatically. Then, we can easily say that if there is a remote machine that we constantly access from within our application, using “Connection: keep-alive” will be efficient and performant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-D76hdS7QXrTVlwEysAbg.png" /></figure><p>Another thing we should not forget is that if we use services where we can manage PHP Processes such as “supervisord, Swoole, Laravel Octane, Symfony Messenger” when we create more than one PHP Process, we should keep in mind that these TCP connections will be opened per PHP Process, for example, the same PHP If we run the codes as 2 different processes, 40 TCP connections will be created as follows. Since processes cannot access each other’s memory areas, a new TCP connection is created for each of them, even if we are requesting the same IP:PORT. Therefore, it is not desirable to create too many new processes when using these services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*2FwnrlPHZoHMtXh9afuk2w.png" /></figure><p>If there is a target that we constantly request, “Connection: keep-alive” is suitable, but for targets that we access several times a day, there is no benefit in keeping the relevant connections open, it is best to close them. For example, the following scenarios may occur.</p><ul><li>An HTTP API from which we want to get currency information.</li><li>The e-mail service we want to access when we want to send an e-mail.</li><li>TCP connections open when we want to send a log somewhere when a critical error occurs.</li></ul><p>In these cases, we can terminate the connection when the request-response cycle is completed by adding a header as follows.</p><pre>curl_setopt($ch[$i], CURLOPT_HTTPHEADER, [&quot;Connection: close&quot;]);</pre><p>As seen in the screenshot, ESTABLISHED TCP connections start to close one by one after receiving the response from the remote machine and are completely eliminated. As a result, we do not have a connection that is ready and that we can use again. Because we won’t be making a request there again anytime soon, there’s no need to keep a connection waiting and waste resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*1KC0YR9AJW9SwJ0qvrVhXg.png" /></figure><h4>Timeout Behavior of HTTP Requests</h4><p><strong>CURLOPT_CONNECTTIMEOUT:</strong> Determines the time it takes to establish a successful connection with a server. So, when curl is trying to connect to a server, it specifies the maximum time the connection should be established. If a connection to the server cannot be established within the specified time, the curl operation times out and returns an error.</p><p><strong>CURLOPT_TIMEOUT:</strong> Specifies the maximum time allowed for a transaction to complete. That is, it determines the total time from initiation to completion of a request. If the operation is not completed within the specified time, the curl operation times out and returns an error.</p><pre>&lt;?php<br>try {<br>    $url = &#39;http://server_web_container/bet&#39;;<br><br>    $data = [<br>        &#39;action&#39; =&gt; &#39;bet&#39;,<br>        &#39;amount&#39; =&gt; 0.10<br>    ];<br><br>    $ch = curl_init($url);<br><br>    curl_setopt($ch, CURLOPT_POST, 1);<br>    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));<br>    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);<br>    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0.5);<br>    curl_setopt($ch, CURLOPT_TIMEOUT, 1);<br><br>    $response = curl_exec($ch);<br><br>    if ($response === false) {<br>        throw new Exception(curl_error($ch));<br>    }<br><br>    curl_close($ch);<br><br>    echo &quot;Request handled successfully&quot; . PHP_EOL;<br>} catch (\Throwable $e) {<br>    echo &quot;[ERROR]: &quot; . $e-&gt;getMessage() . PHP_EOL;<br>}</pre><p>In the code block above, we said that if we cannot establish any connection within 0.5 seconds, we do not proceed directly with the process because there is no need to wait until after that time. If we establish a connection and it does not respond within 1 second, we say that it is of no use to us and close the connection. Because in scenarios where the answers after that period are not important to us, there is no need to keep this PHP process waiting for more than 1 second. Instead of waiting for the other party, he can now try to establish new connections for new transactions. In the scenario here, we get an error like the one below because the server-side returns a response in more than 1 second.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-_IZiINC7pZQo3AcrUrbOg.png" /></figure><p>If you have intensive PHP processes, <strong>CURLOPT_CONNECTTIMEOUT</strong> and <strong>CURLOPT_TIMEOUT</strong> values should be used. Because they will be very efficient for the next operations, there is no need to wait in vain for connections that have not yet responded in the expected time, they will no longer consume resources and make room for the next operations in our machine and application.</p><h4>Laravel + Octane + Openswoole</h4><p>When Laravel Octane and Swoole come together, they create a powerful combination to make Laravel applications faster and more scalable. Swoole acts as a web server running directly within your PHP application rather than web servers like Nginx or Apache, allowing it to handle requests more efficiently rather than launching a separate process for each HTTP request. However, when we create a TCP connection with curl_init, our service files do this for each new HTTP request. For this reason, it is useful to make a few configurations when using this trio to get rid of the creation cost.<br>First, let’s create a service file from which we will make HTTP requests, as follows. It receives a <strong>CurlHandle</strong> object from outside and fulfills the relevant requests thanks to <strong>operateRequest</strong>.</p><pre>&lt;?php<br><br>namespace App\Services;<br><br>use CurlHandle;<br><br>class HttpService<br>{<br>    private CurlHandle $ch;<br><br>    public function __construct(CurlHandle $ch) {<br>        if (!isset($this-&gt;ch)) {<br>            $this-&gt;ch = $ch;<br>        }<br>    }<br>    public function operateRequest($url, $body): bool|string<br>    {<br>        curl_setopt($this-&gt;ch, CURLOPT_URL, $url);<br>        curl_setopt($this-&gt;ch, CURLOPT_RETURNTRANSFER, true);<br>        curl_setopt($this-&gt;ch, CURLOPT_POST, 1);<br>        curl_setopt($this-&gt;ch, CURLOPT_POSTFIELDS, json_encode($body));<br><br>        curl_setopt($this-&gt;ch, CURLOPT_HTTPHEADER, [<br>            &#39;Content-Type: application/json&#39;,<br>            &#39;Connection: keep-alive&#39;<br>        ]);<br><br>        $response = curl_exec($this-&gt;ch);<br><br>        if (curl_errno($this-&gt;ch)) {<br>            return curl_error($this-&gt;ch);<br>        }<br><br>        //curl_close($this-&gt;ch);<br><br>        return $response;<br>    }<br><br>}</pre><p>We have a Controller file like the one below that uses this place. In this application, when a request comes to this controller and method, we make another target <strong>HTTP</strong> request via <strong>HttpService</strong>.</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Services\HttpService;<br><br>class CasinoController extends Controller<br>{<br>    public function getSampleData(HttpService $httpService): \Illuminate\Http\JsonResponse<br>    {<br><br>        $body = [<br>            &#39;title&#39; =&gt; &#39;foo&#39;,<br>            &#39;body&#39; =&gt; &#39;bar&#39;,<br>            &#39;userId&#39; =&gt; 1,<br>        ];<br><br>        $response = $httpService-&gt;operateRequest(&quot;localhost:8080&quot;, $body);<br><br>        $data = json_decode($response, true);<br><br>        if ($data === null) {<br>            return response()-&gt;json([&#39;error&#39; =&gt; &#39;JSON converting error&#39;]);<br>        }<br><br>        return response()-&gt;json($data);<br>    }<br>}</pre><p>In the <strong>AppServiceProvider</strong> file owned by Laravel, we register our service as follows. In this way, instead of being created over and over again when this service is called more than once in the life cycle of 1 request, the first created version will be used. But our goal is not to create a life cycle within 1 request but to ensure that the Controller uses the same example when more than one request comes and does not create the same service over and over again.</p><pre>&lt;?php<br><br>namespace App\Providers;<br><br>use App\Services\HttpService;<br>use Illuminate\Support\ServiceProvider;<br><br>class AppServiceProvider extends ServiceProvider<br>{<br>    /**<br>     * Register any application services.<br>     */<br>    public function register(): void<br>    {<br>        $this-&gt;app-&gt;singletonIf(HttpService::class, function () {<br>            $ch = curl_init();<br>            return new HttpService($ch);<br>        });<br>    }<br><br>    /**<br>     * Bootstrap any application services.<br>     */<br>    public function boot(): void<br>    {<br><br>    }<br>}</pre><p>Let’s first take a look at what happens when we run it this way. What we expect is; to open a new TCP connection for every HTTP request we make to this controller side. When I make 4 HTTP requests and check the TCP connections opened from this application, I see a total of 4 different TCP connections. However, we always make requests to the same target within the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9H3_R8JtB-0aJGiDB1KcKA.png" /></figure><p>To avoid this situation, we need to provide the service file I created for the configuration on the Octane side. In this way, the PHP workers launched by Octane and Swoole will from now on install those services once and will always use the same example wherever needed. We also add HttpService to the warm value in the array we returned in the config/octane.php file.</p><pre>&#39;warm&#39; =&gt; [<br>    ...Octane::defaultServicesToWarm(),<br>    \App\Services\HttpService::class,<br>],</pre><p>This time I made 10 HTTP requests and created only 1 TCP connection for the same target, as shown below. Because HttpService is no longer started for each request, an instance is created once when Octane+Swoole is running, and that instance is used when needed. In this way, we avoid the cost of creating a TCP connection and can make requests over the same connection to the places we constantly make requests to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lx9XBgo5BUnbCaXEXnsskw.png" /></figure><p>If we do not make a request again for a certain period of time, the status of the connection to the same location changes to CLOSE_WAIT. That’s why it is important that we make this configuration for the goals we constantly desire.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJqh9D0ssnQZRCoT9vVGZw.png" /></figure><h4>Symfony + Swoole</h4><p>On the Symfony side, we also have an <strong>HttpService</strong> file as follows. We added the service file <strong>config/services.yaml</strong>. Thus, we include the service we created in Symfony dependency management. Here again, a request is made to the relevant target according to the values received by the Controller. In the Symfony environment run by Swoole, TCP connections are constantly being created and we will change a few lines to get rid of this, but first let’s run this structure and see what happens.</p><pre>parameters:<br><br>services:<br>    _defaults:<br>        autowire: true      # Automatically injects dependencies in your services.<br>        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.<br><br>    App\:<br>        resource: &#39;../src/&#39;<br>        exclude:<br>            - &#39;../src/DependencyInjection/&#39;<br>            - &#39;../src/Entity/&#39;<br>            - &#39;../src/Kernel.php&#39;<br><br>    App\Service\HttpService: ~</pre><pre>&lt;?php<br><br>namespace App\Service;<br><br>class HttpService<br>{<br>    private \CurlHandle $ch;<br>    public function __construct()<br>    {<br>    }<br><br>    public function operateRequest($url, $body): bool|string<br>    {<br>        $this-&gt;ch = curl_init();<br>        curl_setopt($this-&gt;ch, CURLOPT_URL, $url);<br>        curl_setopt($this-&gt;ch, CURLOPT_RETURNTRANSFER, true);<br>        curl_setopt($this-&gt;ch, CURLOPT_POST, 1);<br>        curl_setopt($this-&gt;ch, CURLOPT_POSTFIELDS, json_encode($body));<br><br>        curl_setopt($this-&gt;ch, CURLOPT_HTTPHEADER, [<br>            &#39;Content-Type: application/json&#39;,<br>            &#39;Connection: keep-alive&#39;<br>        ]);<br><br>        $response = curl_exec($this-&gt;ch);<br><br>        if (curl_errno($this-&gt;ch)) {<br>            return curl_error($this-&gt;ch);<br>        }<br><br>        //curl_close($this-&gt;ch);<br>        return $response;<br>    }<br><br>}</pre><p>Our controller file is as follows.</p><pre>&lt;?php<br><br>namespace App\Controller;<br><br>use App\Service\HttpService;<br>use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;<br>use Symfony\Component\HttpFoundation\JsonResponse;<br>use Symfony\Component\Routing\Annotation\Route;<br><br>class DebitController extends AbstractController<br>{<br>    #[Route(&#39;/debit&#39;, name: &#39;app_debit&#39;)]<br>    public function debit(HttpService $httpService): JsonResponse<br>    {<br>        $body = [<br>            &#39;title&#39; =&gt; &#39;foo&#39;,<br>            &#39;body&#39; =&gt; &#39;bar&#39;,<br>            &#39;userId&#39; =&gt; 1,<br>        ];<br><br>        $response = $httpService-&gt;operateRequest(&quot;localhost:8080&quot;, $body);<br><br>        $data = json_decode($response, true);<br><br>        if ($data === null) {<br>            return $this-&gt;json([&#39;error&#39; =&gt; &#39;JSON converting error&#39;]);<br>        }<br><br>        return $this-&gt;json($data);<br>    }<br>}</pre><p>As we make requests here, we can observe that TCP connections are created over and over again, even though they are the same target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYenB_x4LAHpqNQA0IyJow.png" /></figure><p>To avoid this situation, we define the curl value in <strong>__construct</strong> in the service file as follows.</p><pre>&lt;?php<br><br>namespace App\Service;<br><br>class HttpService<br>{<br>    private \CurlHandle $ch;<br>    public function __construct()<br>    {<br>        if (!isset($this-&gt;ch)) {<br>            $this-&gt;ch = curl_init();<br>        }<br>    }<br><br>    public function operateRequest($url, $body): bool|string<br>    {<br><br>        curl_setopt($this-&gt;ch, CURLOPT_URL, $url);<br>        curl_setopt($this-&gt;ch, CURLOPT_RETURNTRANSFER, true);<br>        curl_setopt($this-&gt;ch, CURLOPT_POST, 1);<br>        curl_setopt($this-&gt;ch, CURLOPT_POSTFIELDS, json_encode($body));<br><br>        curl_setopt($this-&gt;ch, CURLOPT_HTTPHEADER, [<br>            &#39;Content-Type: application/json&#39;,<br>            &#39;Connection: keep-alive&#39;<br>        ]);<br><br>        $response = curl_exec($this-&gt;ch);<br><br>        if (curl_errno($this-&gt;ch)) {<br>            return curl_error($this-&gt;ch);<br>        }<br><br>        //curl_close($this-&gt;ch);<br>        return $response;<br>    }<br><br>}</pre><p>Now I keep making requests to the Controller side and avoid having to constantly recreate TCP connections to the same target. Because while Swoole is starting up, our values in the service are defined once and stored in memory as long as the Swoole running life cycle continues. Of course, we should avoid unnecessary definitions and not fill the memory space unnecessarily, but if we have a service from which we will constantly make an HTTP request, keeping it ready will allow us to get rid of the cost of recreating TCP connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8Gph8U4cw6-znvRwxzm8Q.png" /></figure><h4>To Sum Up</h4><p>It is important to open the correct TCP connections in PHP applications because it is the primary communication protocol of many internet-based applications and provides a reliable method of transmitting data. Unnecessary or excessive opening of TCP connections can cause a number of negative consequences. Here are the consequences of such situations:</p><p>Resource Exhaustion: Each TCP connection requires memory and processor resources. Opening unnecessary connections may drain the server’s resources. This may cause the server to slow down and affect other services or users.</p><p>Server Load: Unnecessary connections can cause server overload. Excessive use of server resources may cause the server to crash or become unresponsive.</p><p>Performance Issues: Unnecessary connections can increase network traffic and negatively impact server performance. This may cause users to access services slowly.</p><p>Connection Limits: Servers generally have limits on how many TCP connections they can open at the same time. Unnecessary connections may exceed these limits and deny access to other users.</p><p>Security Vulnerabilities: Unnecessary connections can lead to security vulnerabilities. In particular, links that can be used for phishing or security attacks can compromise the server.</p><p>Data Loss: Unnecessary connections can cause data loss or conflicts in the network. This may affect the reliability of the communication.</p><p>Poor Quality of Service: Unnecessary connections can reduce the overall quality of service of the network. This can cause problems, especially in real-time applications (for example, streaming video or voice communications).</p><p>As a result, opening unnecessary TCP connections can negatively impact both server and network performance. Therefore, it is important to manage links carefully and avoid unnecessary links. It is important to block or properly close unnecessary connections to effectively use network and server resources and reduce security risks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14bef4bf2164" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyn-technology/tcp-connection-practices-in-php-applications-14bef4bf2164">TCP Connection Practices in PHP Applications</a> was originally published in <a href="https://medium.com/beyn-technology">Beyn Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Automation with CI/CD and Jenkins: A Guide]]></title>
            <link>https://medium.com/beyn-technology/testing-automation-with-ci-cd-and-jenkins-a-guide-dd2e5e3abd2d?source=rss----88fe3e34120f---4</link>
            <guid isPermaLink="false">https://medium.com/p/dd2e5e3abd2d</guid>
            <category><![CDATA[robot-framework]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[test]]></category>
            <dc:creator><![CDATA[Hüseyin Solmaz]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 11:38:38 GMT</pubDate>
            <atom:updated>2023-10-10T11:38:38.630Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is CI/CD?</h3><p>Continuous Integration and Continuous Deployment, or CI/CD, is an acronym. It is a collection of guidelines and practices for software development that tries to speed up and automate the procedures for integrating code updates into a shared repository, executing automated tests, and releasing the software into production. CI/CD enables development teams to produce software more quickly and at a higher standard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fG2Spd_pZNEhlcBj.png" /></figure><h3>How is CI/CD used in the testing process?</h3><p>Continuous Integration and Continuous Deployment/Delivery (CI/CD) refers to the tools and processes to automate the testing, building, and delivery of software changes in It is vital that any changes made to the code are tested exhaustively, and deployed to production as soon as possible but with as little manual interaction as necessary, and CI/CD is key to this.In the field of testing, it mostly deals with the CI part, not CD. Here’s how CI/CD is typically used in the testing process:</p><p><strong>Code Integration</strong>: Developers push their new code changes to a version control system (e.g., Git) often. CI/CD systems are notified by these repositories of any changes.</p><p><strong>Automated Builds</strong>: The CI/CD pipeline runs the build process when code changes are detected. This process compiles the code, package the application, and creates deployable artifacts.</p><p><strong>Unit Testing</strong>: After a successful build automated unit tests run. In unit tests individual pieces of the code are tested to ensure they are working correctly in isolation. If any unit tests do, then your pipeline can stop deploying, and developers can be notified.</p><p><strong>Integration Testing</strong>: After unit tests have passed, integration tests may be run in the pipeline. Integration tests ensure the pieces of the application interact as you expect they will. This phase allows for sniffing up problems which are not visible in unit testing.</p><p><strong>Code Analysis and Quality Checks</strong>: They also typically involve code analysis and a check for quality. Code reviews, for example, are automated checks that can verify code style, code complexity, security issues, and compliance with coding standards.</p><p><strong>Automated Testing Environments</strong>: CIE CD can generate and maintain testing environments which accurately reflect the production environment. That way, tests are performed where the software will be executed later on.</p><p><strong>Automated Regression Testing</strong>: CI/CD Pipelines incorporate regression tests, which verify if the latest code modifications cause any new issues and/or break the system in place. Regression issues would be caught using automated test runs.</p><p><strong>User Acceptance Testing (UAT)</strong>: For example, the code changes being put through this pipeline could be deployed to a staging/pre-prod environment where UAT can be done by stakeholders and/or the QA team.</p><p><strong>Deployment to Production</strong>: When all test are green — code changes are auto-deployed to the production environment. It can be done manually or automatically, depending on the policy and the level of confidence they have in the test process.</p><p><strong>Monitoring and Alerting</strong>: Post deployment, CI/CD pipelines can also include monitoring and alerting systems to identify problems in production and take the necessary actions immediately. This is useful for easily identifying and resolving any outstanding issues that may emerge post-deployment.</p><p><strong>Rollbacks</strong>: Since problems can arise in production, CI/CD pipelines frequently have ways to easily revert to a prior version of the software which is known to function correctly.</p><p><strong>Continuous Feedback</strong>: Because of CI/CD, Developers, QA teams and other parties have continuous feedback. Teams have all the test results at hand, as are the code quality metrics, and details about the deployment status, to take the right decision.</p><p>CI/CD significantly increases the efficiency and reliability of the testing process eliminating manual errors and fast delivery of new features and bug fixes to the end-users. It fosters a Test-Driven-Development culture where continuous testing and integration are key principles of modern software development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*5oFYz-B83i4s8xq8.png" /></figure><h3>What is Jenkins?</h3><p>An open-source automation server called Jenkins is frequently used for developing, testing, and distributing software. It offers a framework for automating a number of software development tasks, such as writing and packaging code, running tests, and deploying applications. Jenkins is extremely flexible and can be tailored to various processes because to the large number of plugins and integrations it supports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ociJroEFruN4Tk_8.png" /></figure><h3>How to install Jenkins?</h3><p>To install Jenkins, you can typically follow these steps:</p><ul><li>Download the Jenkins war file or installer suitable for your operating system.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSSf7vcNElSpX-yr5cDBIQ.png" /></figure><ul><li>Install Jenkins setup file downloaded</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*4S-smeZE9HHhFFqHkh__Yg.png" /></figure><ul><li>Select service Logon Credentials</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*haDBzeLc-bKDsyVJwoRmlA.png" /></figure><ul><li>Install any required dependencies (e.g., Java).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*vy1dIUlD9vNpZCU3HUIm_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*hoM8FVhvVQ1jBPKugDXXrg.png" /></figure><ul><li>Access the Jenkins web interface in your browser and complete the setup process by unlocking Jenkins and installing any necessary plugins. (<a href="http://localhost:8080/login?from=%2F">http://localhost:8080/</a>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F17NfU6WCjDHg-J3Qjn0HQ.png" /></figure><ul><li>Select Plugins</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oCyJFOYayuwdCbB67ya3Wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*gHR2horHavDW4A0DaWkx3A.png" /></figure><ul><li>Wait To installation</li><li>Create Admin User</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-GglAaZb8Z-UnyecCuG-_g.png" /></figure><ul><li>User Can Change Instance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N1d0NzqI2KY4gAfNGA_oQQ.png" /></figure><ul><li>Jenkins Installed You can use Jenkins right now…</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbK-wgrCozphWgtjPA8O_A.png" /></figure><h3>How does Robot Framework work with a Jenkins job?</h3><p>To use Robot Framework within a Jenkins job, you can create a Jenkins job or pipeline and configure it to execute the Robot Framework tests. This involves the following steps:<br>Ensure that Jenkins is installed and configured correctly.</p><ul><li>Make that Jenkins is set up and configured properly.</li><li>Install relevant plugins, such as “Workspace Cleanup” and “Robot Framework” plugins.</li><li>Set up a Jenkins process to clone the source code repository that contains the Robot Framework tests.</li><li>Using the “robot” command, add build steps or pipeline stages to execute the Robot Framework tests.</li><li>To facilitate reporting and analysis, publish test results and artifacts to Jenkins.</li></ul><p>Jenkins may be set up to automatically start these jobs in response to code pushes or on a predetermined schedule, enabling continuous integration and testing for your Robot Framework-based test suite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zXrrKqxOOeAcVm_8.jpg" /></figure><h3>How to configure Robotframework Job at Jenkins step by step</h3><p>Step 1: Install Required Jenkins Plugins:</p><ul><li>Launch Jenkins and go to “Manage Jenkins” &gt; “Manage Plugins.”</li><li>In the “Available” tab, search for and install the following plugins:</li><li>“Robot Framework” plugin: This plugin provides support for Robot Framework in Jenkins.</li><li>“Workspace Cleanup” plugin: Optional but helpful for cleaning up workspace after a build.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*lyVWHX1bUCnzqtjV.jpg" /></figure><p>Step 2: Create or Configure a Jenkins Job:</p><ul><li>Click on “New Item” to create a new Jenkins job.</li><li>Enter a name for your job and select the type of job (typically “Freestyle project” or “Pipeline” based on your preference).</li><li>Click “OK” to create the job.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/0*y3lcvSYVymvem_Em.png" /></figure><p>Step 3: Configure the Source Code Repository:</p><ul><li>In the job configuration, under the “Source Code Management” section, choose your version control system (e.g., Git, SVN) and provide the repository URL.</li><li>Configure credentials if necessary.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/0*y_cPXtHZ9GgUwnY_.png" /></figure><p>Step 5: Configure the Build Steps:</p><ul><li>Under the “Build” section, add a build step to execute your Robot Framework tests. This can be done using a “Shell Command” or “Execute Windows batch command,” depending on your platform.</li><li>Use the robot command to run your tests. For example:</li></ul><pre>robot --outputdir results/ path/to/your/tests/</pre><ul><li>You can also specify additional options, such as test tags or output formats.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_xOn_k9QDuseLaat.png" /></figure><p>Step 6: Post-Build Actions:</p><ul><li>In the job configuration, under the “Post-build Actions” section, add a post-build action to archive the Robot Framework test results. Use the “Publish Robot Framework test results” option.</li><li>Specify the path to the test result XML files. For example, results/*.xml.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PyhPZqmeWViCK9jK.jpg" /></figure><p>Step 7: Save and Build:</p><ul><li>Save your job configuration.</li><li>Trigger a build manually to test the configuration.</li></ul><p>Step 8: Schedule Automated Builds (Optional):</p><ul><li>If desired, configure the job to trigger automatically on code commits by setting up webhooks or using polling mechanisms.</li></ul><p>Step 9: View Test Results:</p><ul><li>After running a build, you can view the test results and Robot Framework reports in the Jenkins job’s build history. Jenkins will provide a summary of test pass/fail status and generate detailed reports.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zCMYfs_VFmhYyYHs.png" /></figure><p>That’s it! Now that you’ve set up a Jenkins job to execute Robot Framework tests. Your Jenkins job can be further customized based on the testing and reporting requirements you have.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd2e5e3abd2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyn-technology/testing-automation-with-ci-cd-and-jenkins-a-guide-dd2e5e3abd2d">Testing Automation with CI/CD and Jenkins: A Guide</a> was originally published in <a href="https://medium.com/beyn-technology">Beyn Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom DQL usage with Symfony]]></title>
            <link>https://medium.com/beyn-technology/custom-dql-usage-with-symfony-a62965154172?source=rss----88fe3e34120f---4</link>
            <guid isPermaLink="false">https://medium.com/p/a62965154172</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[doctrine]]></category>
            <category><![CDATA[dql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[symfony]]></category>
            <dc:creator><![CDATA[Oğuzhan KARACABAY]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 12:35:37 GMT</pubDate>
            <atom:updated>2023-09-05T12:35:37.684Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*DZRONSa8pICwOyNA62ZaXg.png" /></figure><p>Hello, in this article I will talk about the usage and benefits of Custom DQL in Symfony.</p><p>First of all, for those who are unfamiliar, I will explain Doctrine and then DQL. Those who are already familiar with this topic can skip this section.</p><p><strong>Doctrine</strong>: It is an ORM (Object Relational Mapping) tool used for PHP applications. It provides us the ability to work in an object-oriented manner, abstracts basic SQL queries, and offers a more intuitive way to interact with database data.</p><p><strong>DQL (Doctrine Query Language)</strong>: It is a specialized query language that forms the foundation of Doctrine ORM. Although it has a structure similar to SQL, its most important feature is the ability to easily write relationships between objects.</p><p>An example of a DQL string:</p><blockquote>SELECT c FROM Customer c JOIN c.orders o WHERE o.totalAmount &gt; 100</blockquote><p>As you can see above, we filtered by joining the Orders relation through the Customer Entity, and we did this in a simple and understandable language.</p><p>Now that we assume everyone has a basic understanding, let’s gradually move on to what Custom DQL is, what it’s used for, and how to write it.</p><p>Custom DQL commands are customized DQL commands. There might be functions that DQL doesn’t provide, and we may want to develop them ourselves. Let’s write a DQL that takes a given string, splits it, and returns the desired index as an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c5445cacb13deefe1a368466a108c6c/href">https://medium.com/media/0c5445cacb13deefe1a368466a108c6c/href</a></iframe><p>In Custom DQLs, there are two functions we need to pay attention to: getSql and parse. In the parse section, we need to specify the components of the function we are creating. The Lexer assists us in this; it recognizes different components (such as keywords, field names, operators, etc.) within the DQL query. It then breaks down these components into pieces for later interpretation and processing. Let&#39;s go through the process step by step.</p><p>First, let’s prepare an example DQL command:</p><blockquote>“SELECT SPLIT_STR(‘a|bb|ccc|dd’, ‘|’, 3) FROM Product e”</blockquote><p>Next, let’s see how this DQL command is processed in the parse() function:</p><blockquote>$parser-&gt;match(Lexer::T_IDENTIFIER);</blockquote><p>In the first step, we try to match our SPLIT_STR function; our functions are also referred to as an IDENTIFIER. When this process is successfully completed, it automatically moves on to the next token.</p><blockquote>$parser-&gt;match(Lexer::T_OPEN_PARENTHESIS);</blockquote><p>In the second step, we look for the opening parenthesis in our function, i.e., the opening parenthesis in SPLIT_STR(.</p><blockquote>$this-&gt;stringExpression = $parser-&gt;StringPrimary();</blockquote><p>In the third step, after the opening parenthesis, we parse the string we want to split, which is our first parameter.</p><blockquote>$parser-&gt;match(Lexer::T_COMMA);</blockquote><p>Then we match the , to look for the second parameter.</p><blockquote>$this-&gt;delimiterExpression = $parser-&gt;StringPrimary();</blockquote><p>We parse the delimiter we will use for splitting (|).</p><blockquote>$parser-&gt;match(Lexer::T_COMMA);</blockquote><p>We match the , again to look for the third parameter.</p><blockquote>$this-&gt;positionExpression = $parser-&gt;ArithmeticPrimary();</blockquote><p>We successfully parse the third parameter.</p><blockquote>$parser-&gt;match(Lexer::T_CLOSE_PARENTHESIS);</blockquote><p>Finally, we match the closing parenthesis ) to finish the parsing process.</p><p>After our parser is processed, we move on to the getSQL function. This function should return a string SQL statement:</p><pre>public function getSql(SqlWalker $sqlWalker)<br>    {<br>        return sprintf(<br>            &#39;REPLACE(SUBSTRING(SUBSTRING_INDEX(%s, %s, %s), &#39; .<br>            &#39;LENGTH(SUBSTRING_INDEX(%s, %s, %s - 1)) + 1), %s, \&#39;\&#39;)&#39;,<br>            $this-&gt;stringExpression-&gt;dispatch($sqlWalker),<br>            $this-&gt;delimiterExpression-&gt;dispatch($sqlWalker),<br>            $this-&gt;positionExpression-&gt;dispatch($sqlWalker),<br>            $this-&gt;stringExpression-&gt;dispatch($sqlWalker),<br>            $this-&gt;delimiterExpression-&gt;dispatch($sqlWalker),<br>            $this-&gt;positionExpression-&gt;dispatch($sqlWalker),<br>            $this-&gt;delimiterExpression-&gt;dispatch($sqlWalker)<br>        );<br>    }</pre><p>With sprintf, we prepare the necessary arrangements and place our parsed DQL data&#39;s expressions into the SQL code. This turns the following code:</p><blockquote>SELECT SPLIT_STR(‘a|bb|ccc|dd’, ‘|’, 3) FROM Product e</blockquote><p>Through DQL processing, it becomes:</p><blockquote>SELECT REPLACE(SUBSTRING(SUBSTRING_INDEX(‘a|bb|ccc|dd’, ‘|’, 3), LENGTH(SUBSTRING_INDEX(‘a|bb|ccc|dd’, ‘|’, 3–1)) + 1), ‘|’, ‘’) AS sclr_0 FROM Products p0_</blockquote><p>Finally, in order for DQL to recognize the SPLIT_STR function, we need to open our doctrine.yaml file and make the following adjustments:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b99723c12163435aa075dd70a9730310/href">https://medium.com/media/b99723c12163435aa075dd70a9730310/href</a></iframe><p>I would like to provide an example related to real-life usage alongside what we have done so far.</p><p>Normally, you cannot execute the GROUP_CONCAT SQL function in DQL because DQL doesn’t recognize the GROUP_CONCAT function, and you would get an error like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DpC4CKes5iOPkF2iBvcdUQ.png" /></figure><p>We were able to solve this situation very easily using Custom DQL:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d58335fae58f6430df345d91c0c0f6b2/href">https://medium.com/media/d58335fae58f6430df345d91c0c0f6b2/href</a></iframe><p>Of course, the specific solution above was evaluated based on our usage of GROUP_CONCAT in the project. This serves as an example of using this Custom DQL:</p><pre>&#39;GROUP_CONCAT((SELECT c.id FROM App\Entity\xx c WHERE pp.value = c.id AND pp.name = \&#39;xxx\&#39;)) as x&#39;,<br>&#39;GROUP_CONCAT((SELECT c2.id FROM App\Entity\yy c2 WHERE pp.value = c2.id AND pp.name = \&#39;yyy\&#39;)) as y&#39;,</pre><p>In summary, writing Custom DQL allows us to create SQL functions that are either not supported by DQL or would normally be complex and lengthy. This makes life easier for us by simplifying the process :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a62965154172" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyn-technology/custom-dql-usage-with-symfony-a62965154172">Custom DQL usage with Symfony</a> was originally published in <a href="https://medium.com/beyn-technology">Beyn Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>