<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Barış Çimen on Medium]]></title>
        <description><![CDATA[Stories by Barış Çimen on Medium]]></description>
        <link>https://medium.com/@bariscimen?source=rss-3075423bc1a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UwFDsmGECO0Zy6W-8qZ4BA.jpeg</url>
            <title>Stories by Barış Çimen on Medium</title>
            <link>https://medium.com/@bariscimen?source=rss-3075423bc1a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 04:26:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bariscimen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[10 Most Common Anti-Patterns Every Software Engineer Must Avoid!]]></title>
            <link>https://bariscimen.medium.com/10-most-common-anti-patterns-every-software-engineer-must-avoid-182091438c2b?source=rss-3075423bc1a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/182091438c2b</guid>
            <category><![CDATA[antipattern]]></category>
            <category><![CDATA[dark-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Barış Çimen]]></dc:creator>
            <pubDate>Sun, 16 May 2021 13:25:02 GMT</pubDate>
            <atom:updated>2021-05-16T13:25:02.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8NZyUmioq2AwQe7pIq8aHA.png" /></figure><p>The extension and maintenance of a system requires a good software structure. Due to the complex nature of software development, the system structure whose architecture and design have been planned and the system structure that is developed may differ from each other. This inconsistency may result in the use of anti-patterns as a solution to the emerging problems, which contrarily causes greater problems. This article will present 10 commonly used anti-patterns in Software Engineering.</p><h3>1. First things first: What is “<strong>Anti-Pattern“</strong>?</h3><p>Anti-patterns are also called “bad practices”, “dark patterns”, or “pitfalls”. The anti-pattern concept has been widely used since Bell Labs programmer <strong>Andrew Koenig</strong> mentioned it in his book “<strong>C Traps and Pitfalls”</strong>. According to Andrew Koenig:</p><blockquote>An anti-pattern is just like a pattern, except that instead of a solution it gives something that looks superficially like a solution, but isn’t one.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/0*4r7eTmEl6FwSML4J.png" /><figcaption>Image credits: martinfowler.com</figcaption></figure><p>Although there are standard design patterns recommended for solving problems in software development, anti-patterns continue to be commonly used, but they are ineffective and/or counterproductive in practice. Knowing anti-pattern concepts makes it easier to anticipate the potential problems in software development processes and take timely actions.</p><h3>2. Anti-Patterns in Software Engineering</h3><p>Anti-pattern examples in software engineering can be listed under five basic categories. The following graph shows these five categories with examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vffj7JH2C96m4c3oaBcmPA.png" /></figure><p>In this section, I will examine 10 most common anti-pattern examples in detail.</p><h4>2.1. Magic PushButton</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*5tvUyOIt32Rh002D" /><figcaption>Image credits: make-everything-ok.com</figcaption></figure><p>The magic pushbutton is one of the most frequently used anti-patterns in software design. Also called “button-click” programming, this anti-pattern is quite common in GUI (Graphical User Interface) based applications (e.g. Windows Forms Programming).</p><p>This approach entails writing the business logic directly within interface code without using abstraction. As a result, the code underlying the Pushbuttons becomes unmanageable, and the reuseability, readability, and testability of the code decreases.</p><h4>2.2. Boat Anchor</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*SdWrMQpQydqTujMu.jpg" /><figcaption>Image credits: divermag.com</figcaption></figure><p>Boat anchor is a piece of software that is kept or left in a project although it does not have any functionality. Typically, this is because the developer thinks that they will need it later. However, this assumption is almost always wrong.</p><p>Forgotten pieces of code can create a big question mark for programmers in the future. After several years, it may no longer be recalled for what purpose they were used or why they were even written in the first place.</p><h4>2.3. Cargo Cult Programming</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v2JsJhYLnghxk8OU.jpeg" /><figcaption>Image credits: soler7.com</figcaption></figure><p>Cargo cult programming refers to the use of software structures, patterns, and methods without a clear understanding of what/how/why.</p><p>The developer implements the software structures, patterns, and methods that are used for a solution without knowing how they work or why they are used. This strict adherence encourages the developer to resort to the same philosophies in other solutions too.</p><p>As a natural consequence of this, the developer moves away from the problem and becomes unable to make the appropriate diagnosis after a while.</p><h4>2.4. Error Hiding</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*OoM2-IJLfjAbcyws" /><figcaption>Image credits: acomaanimalclinictucson.com</figcaption></figure><p>Error hiding refers to catching an error or exception without displaying a meaningful message to the user and deleting the stack trace during exception handling.</p><p>Having received no meaningful notification about the error, the user naturally does not understand the problem. To avoid this, a meaningful error message should be given according to the type of end user and all relevant data about the error should be kept for debugging purposes.</p><h4>2.5. Lava Flow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*e0aDrPRx3ptuE-sX" /><figcaption>Image credits: cassiophong.wordpress.com</figcaption></figure><p>Lava Flow refers to the practice of keeping undesirable, redundant, or low-quality code because removing it would be too costly or have unpredictable consequences.</p><p>Some software projects start for research purposes and then evolve into products. However, these products often turn out to be a historical antiquity of code pieces whose purpose is long forgotten or unknown. This might be because the person who wrote the code has left the company or simply because the developers involved in the project do not remember the purpose for which the relevant piece of code was written.</p><h4>2.6. Spaghetti Code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*qqSyy_72u9h7F2_P" /><figcaption>Image credits: ahajokes.com</figcaption></figure><p>Spaghetti code refers to a source code whose structure is barely comprehensible and difficult-to-maintain, especially due to the misuse of code structures.</p><p>This anti-pattern usually occurs when acting outside a logical design body. This means that object-oriented language capabilities are ignored and a separate function is written for almost every business process.</p><p>The result of this is a code that is far from readable and difficult to follow. This type of code is usually created when programs are constantly updated in their lifecycles, or by inexperienced developers.</p><p>These types of codes are generally not intelligible to anyone other than their developer, and they often need to be rewritten.</p><h4>2.7. God Object (The Blob)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*6W5byhac83_hQbfH.jpg" /><figcaption>Image credits: stroysss.ru</figcaption></figure><p>In object-oriented programming, God objects are objects that know or do too much. These objects have many members and behaviors and can be perceived as the main class of the application. These objects bring too much complexity to the code. In addition, these objects take time to load into memory.</p><h4>2.8. Copy-Paste Programming</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*RjPqnQLjnrd0BtDC.jpg" /><figcaption>Image credits: cuinsight.com</figcaption></figure><p>Copy-paste programming is the production of highly repetitive code via copy and paste operations without creating generic solutions.</p><p>As a result, every change in the main code needs to be applied to wherever the code has been reproduced as well. In addition, updates can be costly, bugs can go unnoticed and the risk increases for the faulty operation of the app.</p><h4><strong>2.9. Golden Hammer</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*X7XtfJX-oS1FsU-I" /><figcaption>Image credits: richmondmagazine.com</figcaption></figure><p>Golden hammer is a well-known solution or concept that is obsessively applied to many software problems.</p><p>It is basically an attempt to apply a solution that has proved to be successful before to new problems. However, it is not always possible to solve problems using the same methods and approaches.</p><p>This might occur when development teams are not aware of technological advances because firms want to avoid the additional cost of training, or simply because some teams do not allow activities and studies that will pave the way for individual development.</p><h4>2.10. Reinventing the Square Wheel</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kYPAdKFUDTvrRZgQ.jpg" /><figcaption>Image credits: mektepp.com</figcaption></figure><p>Reinventing the square wheel refers to the failure to adopt an existing solution and instead adopting a custom solution that performs significantly worse than the existing one.</p><p>There are already standard and specific solutions to certain software problems. Moreover, there are standardized architectural approaches and structures for these solutions. An attempt to produce a solution from scratch instead of using these facilitators is called the reinvention of the wheel. In case of such attempts, the development team usually believes that the problem in question is very special and cannot be addressed with existing practices. Also, the lack of technology transfer and communication between software development teams causes this anti-pattern.</p><h3>3. Conclusion</h3><p>Whether you are a career-starter in software development or you have spent years in the software industry, you might have already encountered some of the anti-pattern scenarios mentioned above or even played an active role in it. Since software development processes, techniques and architectures are constantly developing and changing, anti-pattern cases are simply unavoidable. However, we can deal with these situations more effectively if we are aware of what we are facing. This article presented 10 most common anti-patterns, yet it should be noted that there are many more. It would definitely be useful to learn about them by examining example cases.</p><p>That’s all for the anti-patterns in software engineering, I hope you enjoyed it. Please feel free to leave comments and share the article with others.</p><h3>References</h3><p><a href="https://en.wikipedia.org/wiki/Anti-pattern#Methodological">https://en.wikipedia.org/wiki/Anti-pattern#Methodological</a><br><a href="https://en.wikibooks.org/wiki/Introduction_to_Software_Engineering/Architecture/Anti-Patterns">https://en.wikibooks.org/wiki/Introduction_to_Software_Engineering/Architecture/Anti-Patterns</a><br><a href="https://sourcemaking.com/antipatterns/software-development-antipatterns">https://sourcemaking.com/antipatterns/software-development-antipatterns</a><br><a href="https://www.buraksenyurt.com/post/AntiPatterns-Ders-Notlarc4b1m">https://www.buraksenyurt.com/post/AntiPatterns-Ders-Notlarc4b1m</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=182091438c2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[11 Reasons to Switch from Monolithic to Microservices]]></title>
            <link>https://bariscimen.medium.com/11-reasons-to-switch-from-monolithic-to-microservices-6c1640d46886?source=rss-3075423bc1a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c1640d46886</guid>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[monolithic]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Barış Çimen]]></dc:creator>
            <pubDate>Sun, 22 Nov 2020 13:44:41 GMT</pubDate>
            <atom:updated>2020-11-22T15:02:34.624Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, I will provide a brief overview of Monolithic and Microservice architectures and focus on 11 reasons why you should prefer using Microservice architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__3aAfSEkPe9gKomxUCDZw.png" /><figcaption>Monolith vs. Microservices</figcaption></figure><h3>Monolithic Architecture</h3><p>According to <a href="https://web.archive.org/web/20070902151937/http://www.its.state.nc.us/Information/Glossary/Glossm.asp">ITS</a>, a monolithic architecture is defined as;</p><blockquote>Monolithic architecture is the traditional unified model for the design of a software program. A monolithic application is an application in which the user interface, business rules, and data access code are combined into a single executable program and deployed on one platform. It operates independently from other applications, performing every step of the process needed to complete the entire business function. It does not share any logic or data across the system or organizational boundaries. Databases are designed for access by single application systems within a single agency, not for access by multiple application systems in multiple agencies simultaneously.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*goWhMxQnPVUTOuMb" /><figcaption>Monolithic Architecture Diagram</figcaption></figure><p>In other words, we can briefly describe a <strong>monolithic </strong>application as <em>self-contained and independent from other computing applications.</em> The design philosophy is that the application is responsible for every step required to complete a particular function, rather than a particular task.</p><p>Monolithic architecture is still the most preferred software architecture today. It is especially preferred by newly established start-up companies. We can list the reasons behind this as follows:</p><ul><li>Easy monitoring,</li><li>Quick and easy development and maintenance for small projects,</li><li>Consistent interoperability of the functionalities,</li><li>Easy transaction management.</li></ul><p>However, as the project grows, some problems begin to arise. For example;</p><ul><li>Code duplication and Git Merge complications,</li><li>Shared database,</li><li>Codebase complexity,</li><li>Lack of ownership of code,</li><li>Almost impossible regression testing,</li><li>No possibility to scale a specific functionality,</li><li>A long process from development to deployment,</li><li>More difficult development and maintenance with the increase in the number of teams and employees working on the project.</li></ul><p>Additionally;</p><ul><li>Due to their dependencies on each other, changes made in one functionality can affect others.</li><li>The same programming language and the same frameworks must be used in the application.</li><li>Even with a small change in the application, the entire application must be deployed.</li></ul><h3>Microservice Architecture</h3><p>According to <a href="https://aws.amazon.com/microservices/">AWS</a>, microservice architecture is defined as:</p><blockquote>An architectural and organizational approach to software development where software is composed of small independent services that communicate over well-defined APIs. These services are owned by small, self-contained teams.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sjm4FnLu8SCWE1lk" /><figcaption>Microservice Architecture Diagram</figcaption></figure><p>In short, <strong>microservice</strong> can be defined as <em>individual services that work independently from each other and communicate with each other.</em> Each service carries out its own business logic and does not deal with the business logic of other services. It is an architecture that reduces the burden and complexity of monolithic architecture and offers easier management.</p><p>Communication between services takes place with protocols such as HTTP, HTTPS, AMQP, or a binary protocol like TCP. The appropriate protocol is selected according to the nature of the data to be transferred. Although the HTTP protocol is used in most of the applications developed in the market, the usage of AMQP protocol is increasing with the popularity of message brokers like <a href="https://www.rabbitmq.com/"><strong>RabbitMQ</strong></a> and <a href="https://kafka.apache.org/"><strong>Kafka</strong></a>.</p><p>The advantages of the Microservice architecture are:</p><ul><li>Easy version controlling,</li><li>Independent databases,</li><li>A considerably simple code base of the service, since each service is independent of each other and only has its own business logic,</li><li>Strong ownership of code,</li><li>Possibility of regression testing,</li><li>Possibility to scale a specific functionality,</li><li>The ease of adding new features and maintaining existing code, whether the application is very large or very small because it is sufficient to make changes only within the relevant service,</li><li>More efficient and quicker teamwork since new employees can easily adapt without getting lost in the codebase.</li></ul><p>Additionally,</p><ul><li>Due to their dependencies on each other, changes made in one functionality can affect others.</li><li>Services can be written in different languages and with different frameworks.</li><li>Changes made to one service do not require other services to be re-deployed. It is sufficient to deploy only the relevant service.</li></ul><p>Unfortunately, there is no silver bullet. The microservice architecture has its drawbacks that you may face:</p><ul><li>Increase in system architecture complexity</li><li>Increase in development time for complex features</li><li>Complexity in communication between services</li></ul><h3>Switching from Monolithic to Microservices</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vr-8dsYFuA3Mq0lcvbCPeg.png" /></figure><p>As application development trends continue to evolve, the controversy between microservice architecture and monolithic architecture will only become more pronounced. In the end, developers should analyze the current situation well and understand what is actually needed for their specific use cases.</p><p>For smaller companies, starting with a monolithic architecture can be simpler, faster, and cheaper, and if the product is not very mature, it can be switched to microservices at a convenient time. Large companies with millions of users are clear examples of the best use case for microservices as they must provide uptime and scalability that the added modularity can provide.</p><p>That’s all for the monolithic and microservice architectures, I hope you enjoyed it. Please feel free to leave comments and share the article with others.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c1640d46886" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Facade Design Pattern in PHP]]></title>
            <link>https://bariscimen.medium.com/facade-design-pattern-in-php-927495bb24cc?source=rss-3075423bc1a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/927495bb24cc</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[facade-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Barış Çimen]]></dc:creator>
            <pubDate>Fri, 23 Oct 2020 18:46:15 GMT</pubDate>
            <atom:updated>2020-10-23T18:46:15.959Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zfphsc10fRscfOiT_mDQtw.png" /><figcaption>Facade Design Pattern in PHP</figcaption></figure><p><strong>Facade Design Pattern</strong> is one of the <strong>structural design patterns</strong> in Software Engineering. Provides a simplified, higher-level interface to a subsystem. Clients can talk to the facade rather than individual classes in the subsystem.</p><h3>What is the Facade Design Pattern?</h3><p>Gang of Four (GOF) defines it as:</p><blockquote>Provide a unified interface to a set of interfaces in a subsystem. Facade Pattern defines a higher-level interface that makes the subsystem easier to use.</blockquote><p>Suppose we have an application with a set of operations to send a message to a Notification Server, like connecting, authenticating, sending, and disconnecting.</p><p>So we will need to perform these operations whenever we want to send a message to the Notification Server. However, this increases the complexity of the code. For this reason, the client application will find it difficult to manage it.</p><p>So we can apply Facade design pattern here and provide a higher-level interface that makes the subsystem easier to use.</p><p>The facade design pattern can basically be represented in UML as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4cKGSfgD78qVh_4dB13vQw.png" /><figcaption>A Demonstration of Facade Design Pattern in UML</figcaption></figure><h3>Facade Design Pattern PHP Example</h3><p>We will make a simple application to demonstrate Facade Design Pattern in PHP. We will create a Facade for a subsystem that is used for the communication between the client and the Notification Server.</p><p>Here is our subsystem:</p><pre>&lt;?php<br><br>namespace App;<br><br>class AuthToken<br>{<br>    <br>}<br><br>class Connection<br>{<br>    public function disconnect()<br>    {<br><br>    }<br>}</pre><pre>class Message<br>{<br>    private $message;<br><br>    <em>/**<br>     * Message constructor.<br>     * </em><strong><em>@param </em></strong><em>$message<br>     */<br>    </em>public function __construct($message)<br>    {<br>        $this-&gt;message = $message;<br>    }<br><br>}</pre><pre>class NotificationServer<br>{<br>    <em>/**<br>     * </em><strong><em>@param </em></strong><em>string $ipAddress<br>     * </em><strong><em>@return </em></strong><em>Connection<br>     */<br>    </em>public function connect(string $ipAddress): Connection<br>    {<br>        return new Connection();<br>    }<br><br>    <em>/**<br>     * </em><strong><em>@param </em></strong><em>string $appID<br>     * </em><strong><em>@param </em></strong><em>string $key<br>     * </em><strong><em>@return </em></strong><em>AuthToken<br>     */<br>    </em>public function authenticate(string $appID, string $key): AuthToken<br>    {<br>        return new AuthToken();<br>    }<br><br>    <em>/**<br>     * </em><strong><em>@param </em></strong><em>AuthToken $authToken<br>     * </em><strong><em>@param </em></strong><em>Message $message<br>     * </em><strong><em>@param </em></strong><em>string $target<br>     */<br>    </em>public function send(AuthToken $authToken, Message $message, string $target)<br>    {<br>        echo &quot;Sending a message&quot; . <em>PHP_EOL</em>;<br>    }<br>}</pre><p>In this example, whenever we want to send a message, we should create an instance of NotificationServer class, connect the server, authenticate, send the message, and disconnect from the server. But, this situation can increase the complexity of the code. Thus, we apply Facade design pattern to provide a higher-level interface where clients can talk to it rather than individual classes in the subsystem.</p><p>The facade class is as follows:</p><pre>&lt;?php<br><br>namespace App;<br><br>class NotificationService<br>{<br>    <em>/**<br>     * A wrapper method to send a message to Notification Server<br>     *<br>     * </em><strong><em>@param </em></strong><em>string $message<br>     * </em><strong><em>@param </em></strong><em>string $target<br>     */<br>    </em>public function send(string $message, string $target)<br>    {<br>        $server = new NotificationServer();<br>        $connection = $server-&gt;connect(&quot;ip&quot;);<br>        $authToken = $server-&gt;authenticate(&quot;appID&quot;, &quot;key&quot;);<br>        $server-&gt;send($authToken, new Message($message), $target);<br>        $connection-&gt;disconnect();<br>    }<br>}</pre><p>Finally, we can use the facade whenever we want to send a message to the Notification Server in the code. Here is the example usage of the Facade:</p><pre>$service = new \App\NotificationService();<br>$service-&gt;send(&quot;Hello World&quot;, &quot;target&quot;);</pre><p>That’s all for the Facade Design Pattern in PHP, I hope you enjoyed it. Please feel free to leave comments and share the article with others.</p><p><em>Go to Github repository of example application here: <br></em><a href="https://github.com/bariscimen/FacadePatternPHP">https://github.com/bariscimen/FacadePatternPHP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=927495bb24cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observer Design Pattern in PHP]]></title>
            <link>https://bariscimen.medium.com/observer-design-pattern-in-php-714f9299bf76?source=rss-3075423bc1a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/714f9299bf76</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <dc:creator><![CDATA[Barış Çimen]]></dc:creator>
            <pubDate>Sun, 18 Oct 2020 14:09:35 GMT</pubDate>
            <atom:updated>2020-10-18T14:09:35.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ckBCscymmBWstFeh1DxotA.png" /></figure><p><strong>Observer Design Pattern</strong> is one of the <strong>behavioral design patterns</strong> in Software Engineering. The observer design pattern is useful when you are concerned with the state of an object and want to be notified of any changes. In the observer pattern, the object that monitors the state of another object is called the <strong>Observer</strong>, and the tracked object is called the <strong>Subject</strong>.</p><h3>What is the Observer Design Pattern?</h3><p>Gang of Four (GOF) defines it as:</p><blockquote>Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.</blockquote><p><strong>Subject</strong> includes a list of observers to notify any changes in its state, so it must provide methods by which observers can attach and detach their own. The subject also includes a method for notifying all observers of any changes and can either send the update while notifying the observer or provide another method to receive the update.</p><p><strong>Observer</strong> must have a method for setting the object to be tracked and another method that will be used by the Subject to inform them about any updates.</p><p>The observer design pattern can basically be represented in UML as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7iLnW_wPoJkAS987mwGGg.png" /><figcaption>A Demonstration of Observer Design Pattern in UML</figcaption></figure><p>Observer Design Pattern is also called as publish-subscribe pattern.</p><p>As an example, Model-View-Controller (MVC) frameworks use the Observer Design Pattern where Model is the Subject and Views are observers that can attach to get notified of any change to the model.</p><h3>Observer Design Pattern PHP Example</h3><p>As an example of Observer Design Pattern in PHP, we will make a simple scoreboard application in which Matches are Subjects and Scoreboards are Observers that can attach to these matches. When a match score is updated, scoreboards that have attached to this match should also be updated.</p><p>Demonstration of our example scoreboard application in UML:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tXHTEautQRuKwggt_xxv7A.png" /><figcaption>UML Diagram of Scoreboard Application Example</figcaption></figure><p>Based on the requirements of Subject, here is the base Subject interface that defines the contract methods to be implemented by any concrete subject.</p><pre>&lt;?php<br><br>namespace App;<br><br>abstract class Subject<br>{<br>    protected $observers = [];<br><br>    public function attach(Observer $observer)<br>    {<br>        $this-&gt;observers[] = $observer;<br>    }<br><br>    public function detach(Observer $observer)<br>    {<br>        $this-&gt;observers = array_diff($this-&gt;observers, [$observer]);<br>    }<br><br>    public function notify()<br>    {<br>        foreach ($this-&gt;observers as $observer) {<br>            $observer-&gt;update();<br>        }<br>    }<br><br>}</pre><p>Next, we will create a contract for Observer, there will be a method to attach the Subject to the observer and another method to be used by Subject to notify of any change.</p><pre>&lt;?php<br><br>namespace App;<br><br>interface Observer<br>{<br>    public function update();<br>}</pre><p>Now our contracts are ready, let’s proceed with the concrete implementation of Match in our example.</p><pre>&lt;?php<br><br>namespace App;<br><br>class Match extends Subject<br>{<br>    private $homeTeam;<br>    private $awayTeam;<br>    private $homeTeamScore;<br>    private $awayTeamScore;<br><br>    <em>/**<br>     * Match constructor.<br>     * </em><strong><em>@param </em></strong><em>$homeTeam<br>     * </em><strong><em>@param </em></strong><em>$awayTeam<br>     */<br>    </em>public function __construct($homeTeam, $awayTeam)<br>    {<br>        $this-&gt;homeTeam = $homeTeam;<br>        $this-&gt;awayTeam = $awayTeam;<br>        $this-&gt;homeTeamScore = 0;<br>        $this-&gt;awayTeamScore = 0;<br>    }<br><br>    <em>/**<br>     * Increments Home Team&#39;s Score<br>     */<br>    </em>public function incrementHomeTeamScore()<br>    {<br>        $this-&gt;homeTeamScore++;<br>        $this-&gt;notify();<br>    }<br><br>    <em>/**<br>     * Increments Away Team&#39;s Score<br>     */<br>    </em>public function incrementAwayTeamScore()<br>    {<br>        $this-&gt;awayTeamScore++;<br>        $this-&gt;notify();<br>    }<br><br>    <em>/**<br>     * </em><strong><em>@return </em></strong><em>mixed<br>     */<br>    </em>public function getHomeTeam()<br>    {<br>        return $this-&gt;homeTeam;<br>    }<br><br>    <em>/**<br>     * </em><strong><em>@return </em></strong><em>mixed<br>     */<br>    </em>public function getAwayTeam()<br>    {<br>        return $this-&gt;awayTeam;<br>    }<br><br>    <em>/**<br>     * </em><strong><em>@return </em></strong><em>int<br>     */<br>    </em>public function getHomeTeamScore()<br>    {<br>        return $this-&gt;homeTeamScore;<br>    }<br><br>    <em>/**<br>     * </em><strong><em>@return </em></strong><em>int<br>     */<br>    </em>public function getAwayTeamScore()<br>    {<br>        return $this-&gt;awayTeamScore;<br>    }<br><br><br>}</pre><p>Lastly, here is the concrete implementation of Scoreboard that will watch over the updates of matches.</p><pre>&lt;?php<br><br>namespace App;<br><br>class Scoreboard implements Observer<br>{<br>    private $matches = [];<br>    private $name;<br><br>    <em>/**<br>     * ScoreBoard constructor.<br>     * </em><strong><em>@param </em></strong><em>$name<br>     */<br>    </em>public function __construct($name)<br>    {<br>        $this-&gt;name = $name;<br>    }<br><br>    <em>/**<br>     * </em><strong><em>@param </em></strong><em>Match $match<br>     */<br>    </em>public function addMatch(Match $match)<br>    {<br>        $match-&gt;attach($this);<br>        $this-&gt;matches[] = $match;<br>    }<br><br>    <em>/**<br>     * </em><strong><em>@param </em></strong><em>Match $match<br>     */<br>    </em>public function removeMatch(Match $match)<br>    {<br>        $match-&gt;detach($this);<br>        $this-&gt;matches = array_diff($this-&gt;matches, [$match]);<br>    }<br><br>    <em>/**<br>     * Display the Scoreboard<br>     */<br>    </em>public function show()<br>    {<br>        echo &quot;Scoreboard: $this-&gt;name&quot; . <em>PHP_EOL</em>;<br>        foreach ($this-&gt;matches as $match) {<br>            echo str_pad($match-&gt;getHomeTeam(), 20, &quot; &quot;, <em>STR_PAD_LEFT</em>);<br>            echo &quot; &quot; . $match-&gt;getHomeTeamScore();<br>            echo &quot; - &quot;;<br>            echo $match-&gt;getAwayTeamScore() . &quot; &quot;;<br>            echo $match-&gt;getAwayTeam() . <em>PHP_EOL</em>;<br>        }<br>    }<br><br>    <em>/**<br>     * Run when a match is updated.<br>     */<br>    </em>public function update()<br>    {<br>        echo &quot;A match score has changed.&quot; . <em>PHP_EOL</em>;<br>        $this-&gt;show();<br>    }<br>}</pre><p>Finally, here is a simple test program to demonstrate its functionality.</p><pre>&lt;?php<br><br>require <em>__DIR__ </em>. &#39;/vendor/autoload.php&#39;;<br><br>$match1 = new \App\Match(<br>    &quot;Galatasaray&quot;,<br>    &quot;Fenerbahçe&quot;<br>);<br><br>$match2 = new \App\Match(<br>    &quot;Barcelona&quot;,<br>    &quot;Real Madrid&quot;<br>);<br><br>$match3 = new \App\Match(<br>    &quot;Milan&quot;,<br>    &quot;Inter&quot;<br>);<br><br>$scoreBoard1 = new \App\Scoreboard(&quot;SB1&quot;);<br>$scoreBoard1-&gt;addMatch($match1);<br>$scoreBoard1-&gt;addMatch($match2);<br>$scoreBoard1-&gt;show();<br><br>$scoreBoard2 = new \App\Scoreboard(&quot;SB2&quot;);<br>$scoreBoard2-&gt;addMatch($match1);<br>$scoreBoard2-&gt;addMatch($match3);<br>$scoreBoard2-&gt;show();<br><br>$match1-&gt;incrementHomeTeamScore();<br>$match2-&gt;incrementAwayTeamScore();<br>$match3-&gt;incrementAwayTeamScore();</pre><p>When we run the above program, we get the following output.</p><pre>Scoreboard: <em>SB1<br>         Galatasaray </em>0 - 0 <em>Fenerbahçe<br>           Barcelona </em>0 - 0 <em>Real Madrid<br></em>Scoreboard: <em>SB2<br>         Galatasaray </em>0 - 0 <em>Fenerbahçe<br>               Milan </em>0 - 0 <em>Inter<br>A match score has changed</em>.<br><em>Scoreboard</em>: <em>SB1<br>         Galatasaray </em>1 - 0 <em>Fenerbahçe<br>           Barcelona </em>0 - 0 <em>Real Madrid<br>A match score has changed</em>.<br><em>Scoreboard</em>: <em>SB2<br>         Galatasaray </em>1 - 0 <em>Fenerbahçe<br>               Milan </em>0 - 0 <em>Inter<br>A match score has changed</em>.<br><em>Scoreboard</em>: <em>SB1<br>         Galatasaray </em>1 - 0 <em>Fenerbahçe<br>           Barcelona </em>0 - 1 <em>Real Madrid<br>A match score has changed</em>.<br><em>Scoreboard</em>: <em>SB2<br>         Galatasaray </em>1 - 0 <em>Fenerbahçe<br>               Milan </em>0 - 1 <em>Inter</em></pre><p>That’s all for the Observer Design Pattern in PHP, I hope you enjoyed it. Please feel free to leave comments and share the article with others.</p><p><em>Go to Github repository of example application here: </em><a href="https://github.com/bariscimen/ObserverPatternPHP">https://github.com/bariscimen/ObserverPatternPHP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=714f9299bf76" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>