<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Continuous Learning]]></title><description><![CDATA[Follow me along learning new things every day.]]></description><link>https://d.aniel.me/cke/</link><image><url>https://d.aniel.me/cke/favicon.png</url><title>Continuous Learning</title><link>https://d.aniel.me/cke/</link></image><generator>Ghost 4.41</generator><lastBuildDate>Sun, 19 Apr 2026 12:50:35 GMT</lastBuildDate><atom:link href="https://d.aniel.me/cke/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Avoid arrays in your domain and create iterable classes instead]]></title><description><![CDATA[<p>PHP&apos;s <code>array</code> is a powerful datatype. You can add and remove values of any type at any time. This comes at a cost though: You have no control over what is allowed and what not. This can become a problem in your domain code where you need to</p>]]></description><link>https://d.aniel.me/cke/custom-classes-for-iterables/</link><guid isPermaLink="false">6239f6f1b2b3440143999ba1</guid><category><![CDATA[Development]]></category><category><![CDATA[PHP]]></category><dc:creator><![CDATA[Daniel Mecke]]></dc:creator><pubDate>Sun, 22 Sep 2019 12:54:51 GMT</pubDate><content:encoded><![CDATA[<p>PHP&apos;s <code>array</code> is a powerful datatype. You can add and remove values of any type at any time. This comes at a cost though: You have no control over what is allowed and what not. This can become a problem in your domain code where you need to define very strict rules about your domain. If you pass an <code>array</code> of <code>User</code> objects into a method, is it allowed to contain users who are inactive? If you want the array to be sorted (the user with the latest registration date for example), you cannot assume that the calling code has already done that.</p><p>But there is a solution to this problem: You can create a class which implements the <code>\Traversable</code> interface of PHP. The class needs to implement a <code>getIterator(): Traversable</code> method now, so you have full control over how it&apos;s elements are handled by external code. Encapsulating your iterables into their own classes might seem to bloat your code at first. But while this approach indeed comes with additional code, it has some major advantages.</p><p></p><h1 id="advantages">Advantages</h1><h2 id="internal-type-safety">Internal type safety</h2><p>When you encapsulate the concept of a list of <code>User</code> objects into it&apos;s own class, you can easily make sure to only allow <code>User</code> objects to be part of the list. Throw an exception if a different type is passed into it. Now you never have to do any type checks in the code that uses your iterable object.</p><h2 id="constrained-access-options">Constrained access options</h2><p>You have full control over which methods you add to your class. You don&apos;t have to worry that elements of your object are modified in a way you did not intend. Yes, you need to write those methods by yourself, but this gives you the power to decide for each individual case what is needed and what not.</p><h2 id="external-type-safety">External type safety</h2><p>If your code gets an <code>array</code> passed in, you don&apos;t really know what you get. You need to look at the calling code and hope that it does not change. But if you get a custom <code>UserList</code> for example, you know exactly what it&apos;s possibilities and restrictions are.</p><h2 id="encapsulation-of-business-logic">Encapsulation of business logic</h2><p>Often you need to perform the same operation on a list of objects multiple times, for example filter down a list of all users to only those with an active account. This code tends to go into service classes or - even worse - into controllers and other application layer code. Encapsulating these business rules into your iterable classes makes them easy to test and reuse. The calling code is also very straightforward to read: <code>$users-&gt;filterOnlyActive()</code>.</p><h2 id="immutability">Immutability</h2><p>Writing your own methods enables you to always return a new object instead of modifying the existing one. This way you don&apos;t have to worry to break existing code when working with an iterable object.</p><h2 id="sorting">Sorting</h2><p>In an <code>array</code> you don&apos;t have information about it&apos;s sorting. While you can sort an <code>array</code> you need to do it directly in the code that uses it to make sure it wasn&apos;t modified elsewhere. By creating a dedicated class for a sorted list (e.g. <code>SortedUserByAgeList</code>) which makes sure the elements are always in the correct order you don&apos;t need to worry about it in the calling code any more.</p><p></p><h1 id="disadvantages">Disadvantages</h1><h2 id="more-code">More Code</h2><p>This one is pretty straightforward: You need to write those classes. If you don&apos;t have a complex domain model and you don&apos;t intend your application to be maintained for a long time, this might be overkill. But as soon as these classes exist, the improved readability and safety kicks in.</p><h2 id="performance">Performance</h2><p>This one is more critical. The additional type checks and method calls make the execution of the code slower than using simple arrays. If this is a problem or not simply comes down to the use case and needs some profiling. Don&apos;t just dismiss the idea because of premature optimization.</p><p></p><h1 id="summary">Summary</h1><p>I&apos;ve been using this approach in multiple projects over the last few years and it made my code much more readable and safe. I use it mainly in my domain layer where safety is a must and I found that I could simplify the calling code in many places by moving business logic into my iterable classes.</p><p>In my first approaches I used a base class that provided a type check in the constructor and all the common methods for filtering, mapping, counting, etc. But this caused a huge inheritance tree which in turn caused many methods to exist only for a few subclasses and made adjustments very hard. Then I shifted the concept to a simple class that provides the common functionality but is instead used by the custom classes. This way I can decide for every custom class which methods to expose and just forward the method calls to the underlying generic one. Very specific methods are then handled by the custom classes on their own.</p><p>Now that I&apos;ve come to a point where the structure of the generic classes do not change that much any more I extracted them into their own library: <a href="https://packagist.org/packages/cunningsoft/generic-list">https://packagist.org/packages/cunningsoft/generic-list</a>.</p>]]></content:encoded></item><item><title><![CDATA[Dependency Injection: Constructor Injection vs. Setter Injection]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>Your might have heard of phrases like <em>Dependency Injection</em>, <em>Constructor Injection</em> and <em>Setter Injection</em>. These sound a bit confusing at first, but at the end, the concepts are very simple, but also very powerful.</p>
<h2 id="dependencyinjection">Dependency Injection</h2>
<p>First, let me explain the phrase <strong>Dependency Injection</strong>, because it&apos;s maybe the</p>]]></description><link>https://d.aniel.me/cke/dependency-injection-constructor-injection-vs-setter-injection/</link><guid isPermaLink="false">6239f6f1b2b3440143999b9b</guid><category><![CDATA[Development]]></category><category><![CDATA[PHP]]></category><dc:creator><![CDATA[Daniel Mecke]]></dc:creator><pubDate>Wed, 25 May 2016 00:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>Your might have heard of phrases like <em>Dependency Injection</em>, <em>Constructor Injection</em> and <em>Setter Injection</em>. These sound a bit confusing at first, but at the end, the concepts are very simple, but also very powerful.</p>
<h2 id="dependencyinjection">Dependency Injection</h2>
<p>First, let me explain the phrase <strong>Dependency Injection</strong>, because it&apos;s maybe the simplest one and you most likely already use it every day. Let&apos;s say we have a <code>Validator</code> class which somehow validates things. Now we also have a <code>Translator</code> class, which translates things somehow. As we know that <em>separation of concerns</em> is a good thing, they are decoupled - the <code>Validator</code> does know nothing about translating things and the <code>Translator</code> does know nothing about validating things. But we might also want to translate the things that were validated. So the <code>Validator</code> needs some help from the <code>Translator</code> - it <em>depends</em> on it or it has a <em>dependency</em>. To give the <code>Validator</code> access to the <code>Translator</code> we pass it in - or <em>inject</em> it. We <em>inject</em> a <em>dependency</em>. That&apos;s all what <em>dependency injection</em> is, passing objects to other objects.</p>
<h2 id="setterinjection">Setter Injection</h2>
<p>Now we have several ways to achieve this. We could simply pass it every time something is validated, for example <code>$validator-&gt;validate($someObject, $translator)</code>, but this clutters the <code>validate</code>-method and is not very intuitive. Instead, we could store the dependency as a property of the <code>Validator</code>. Now to pass it in we simply use a setter like <code>$validator-&gt;setTranslator($translator)</code>. After we have done this we can call the <code>validate</code>-method as often as we like and it will always use the passed <code>Translator</code>. The <code>Validator</code> now looks something like this:</p>
<pre><code class="language-php">class Validator
{
    private $translator;

    public function setTranslator($translator)
    {
        $this-&gt;translator = $translator;
    }

    public function validate($someObject)
    {
        // do the magic here with the help of $this-&gt;translator
    }
}
</code></pre>
<p>That is all that setter injection is. Now this is great for <strong>optional dependencies</strong>. In our example the <code>validate</code>-method should also work fine with no <code>Translator</code> set because there is no guarantee it has been set before the <code>validate</code>-method has been called!<br>
But what if we want to enforce that?</p>
<h2 id="constructorinjection">Constructor Injection</h2>
<p>If you have a dependency that you cannot leave away because your class does not work without it, <em>constructor injection</em> is the way to go. Instead of calling a set method, the dependency is passed via the constructor. Now there is no way around, but passing it when an object is created. This means for our example that we have to pass a <code>Translator</code> to the <code>Validator</code> in its constructor. This will look something like this:</p>
<pre><code class="language-php">class Validator
{
    private $translator;

    public function __construct($translator)
    {
        $this-&gt;translator = $translator;
    }

    public function validate($someObject)
    {
        // do the magic here with the help of $this-&gt;translator
    }
}
</code></pre>
<p><em>Constructor Injection</em> is great for <strong>obligatory dependencies</strong>. You clearly communicate to the user of that class: You have to pass me such an object, otherwise, I won&apos;t work.</p>
<h2 id="sowhatshouldiuse">So what should I use?</h2>
<p>It absolutely depends on the use case. While in many situations a class simply does not work without its dependencies, it&apos;s perfectly fine to leave them away in other. For example, your <code>Validator</code> might not work without a <code>Translator</code>, because you always want to display the errors to your users. On the other hand it maybe also has a dependency on a <code>Logger</code> class which is able to write the errors to a log file or send it via email. But this might be completely optional.</p>
<h2 id="interfaces">Interfaces</h2>
<p>At the beginning, I said that the <code>Validator</code> should know nothing about how to translate things. But now we have a hard dependency to the <code>Translator</code>. But what if we want to use a different implementation at some point? This might be more obvious with the example of a <code>Logger</code>, so let&apos;s talk about that one. So our <code>Validator</code> is also able to log its results to a log file. We used <em>setter injection</em> here to pass in a <code>FileLogger</code>:</p>
<pre><code class="language-php">class Validator
{
    private $logger;

    public function setLogger(FileLogger $logger)
    {
        $this-&gt;logger = $logger;
    }
}
</code></pre>
<p>That&apos;s fine - until we decide that we need to be informed about the results via email instead of having to look through the log files manually. Now we need to edit the <code>Validator</code>-class to pass in an <code>EmailLogger</code> instead. That&apos;s a bad thing because editing existing code always has the risk to break something. And after all, we just want to change the way we log things - why do we need to change a <code>Validator</code> for that?</p>
<p><strong>Interfaces</strong> to the rescue: Instead of type hinting for the concrete implementation of the <code>FileLogger</code> in our <code>Validator</code>-class we type hint for the interface <code>Logger</code>. Now our <code>FileLogger</code> and <code>EmailLogger</code> simply implement that interface and we are free to change the logger we pass as often as we want - without changing a single line of the <code>Validator</code> code.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Simple Wrapper]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>We write conditionals all the time. Often, we check for very simple things, not worth any extra effort of encapsulation. But in many cases, this makes perfect sense even for very basic things. Let me give you an example:</p>
<pre><code>$date = new \DateTime(&apos;2016-05-15&apos;);
if ($date-&gt;format(&apos;</code></pre>]]></description><link>https://d.aniel.me/cke/simple-wrapper/</link><guid isPermaLink="false">6239f6f1b2b3440143999b97</guid><category><![CDATA[Development]]></category><category><![CDATA[PHP]]></category><dc:creator><![CDATA[Daniel Mecke]]></dc:creator><pubDate>Fri, 13 May 2016 00:00:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>We write conditionals all the time. Often, we check for very simple things, not worth any extra effort of encapsulation. But in many cases, this makes perfect sense even for very basic things. Let me give you an example:</p>
<pre><code>$date = new \DateTime(&apos;2016-05-15&apos;);
if ($date-&gt;format(&apos;N&apos;) == 6 || $date-&gt;format(&apos;N&apos;) == 7) {
    // do something
}
</code></pre>
<p>If you are like me, you always have to look up, that <code>N</code> is the character you need when you want to check for a specific day of the week. Or was it <code>w</code>? Well, yes, but then the Sunday is represented as <code>0</code> instead of <code>7</code>. Whoo, lots of boring stuff to remember.</p>
<p>Now even if this is the only place in your entire code base that needs this check, this will always be a place where a fellow developer or your future self will stop and needs to think for some seconds what this means.</p>
<p>Now consider this:</p>
<pre><code>$date = new DateTime(&apos;2016-05-15&apos;);
if ($date-&gt;isWeekend()) {
    // do something
}
</code></pre>
<h2 id="inheritance">Inheritance</h2>
<p>This is way better to read, no need to think about that at all. If you own that class by yourself you can of course simply add that functionality. But in case you do not, all you need to do is to extend the class you want to do the check on.</p>
<pre><code>namespace MyApp;

class DateTime extends \DateTime
{
    public function isWeekend()
    {
        return $this-&gt;format(&apos;N&apos;) == 6 || $this-&gt;format(&apos;N&apos;) == 7;
    }
}
</code></pre>
<p>Now you never have to worry about the characters to use in the <code>format</code>-method or what numbers to use.</p>
<h2 id="delegation">Delegation</h2>
<p>While inheritance seems the easiest way to achieve this, it comes with a drawback. Your class now completely depends on changes of the original underlying class. If for some reason the public API of it changes, your public API changes as well.</p>
<p>So instead you could use delegation:</p>
<pre><code>namespace MyApp;

class DateTime
{
    private $dateTime;

    public function __construct(\DateTime $dateTime)
    {
        $this-&gt;dateTime = $dateTime;
    }

    public function isWeekend()
    {
        return $this-&gt;format(&apos;N&apos;) == 6 || $this-&gt;format(&apos;N&apos;) == 7;
    }

    public function format($format)
    {
        return $this-&gt;dateTime-&gt;format($format);
    }
}
</code></pre>
<p>Now you when the public API of the underlying class changes, only your wrapper breaks - but not your whole application. The drawback here is that you have to delegate all the methods you want to use. This might seem stupid at first glance, but it gives you the complete control over what can be done with your class and what not.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item></channel></rss>