<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Alain Schlesser</title><description>Architectural rigor for the age of intelligent machines. 25 years of systems thinking, applied to systems that think.</description><link>https://www.alainschlesser.com/</link><item><title>Using Bento Components in Gutenberg Blocks</title><link>https://www.alainschlesser.com/thinking/using-bento-components-in-gutenberg-blocks/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/using-bento-components-in-gutenberg-blocks/</guid><description>I have spent the weekend of March 19th to 21st at the CloudFest Hackathon in Rust, where I had submitted a project together with Pascal Birchler ( @swissspidy ). It wa...</description><pubDate>Fri, 08 Apr 2022 00:00:00 GMT</pubDate><content:encoded>
&lt;p&gt;I have spent the weekend of March 19th to 21st at the CloudFest Hackathon in Rust, where I had submitted a project together with Pascal Birchler (&lt;a href=&quot;https://twitter.com/swissspidy&quot; rel=&quot;noreferrer noopener&quot;&gt;@swissspidy&lt;/a&gt;). It was lots of fun and producing many interesting insights for me personally as well as for the team, so I&apos;d like to share a few of my impressions here.&lt;/p&gt;


&lt;figure&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2022/04/IMG_3464-1-1024x768.jpg&quot; alt=&quot;&quot; /&gt;&lt;figcaption&gt;Pascal Birchler &amp;amp; Alain Schlesser on stage presenting the Bento + WordPress project.&lt;/figcaption&gt;&lt;/figure&gt;


&lt;h2&gt;What is the Cloudfest Hackathon?&lt;/h2&gt;


&lt;p&gt;The global cloud computing industry comes together each year in the &lt;a href=&quot;https://www.europapark.de/en&quot; rel=&quot;noreferrer noopener&quot;&gt;Europa-Park Resort&lt;/a&gt; in Rust to celebrate the &lt;a href=&quot;https://www.cloudfest.com/&quot; rel=&quot;noreferrer noopener&quot;&gt;Cloudfest&lt;/a&gt; (formerly World Hosting Days). This event is happening in an amusement park that is still closed off to the public, with all of the attractions being reserved for the attendees! 😁&lt;/p&gt;


&lt;p&gt;Leading up to the Cloudfest on the weekend immediately prior, there is traditionally the &lt;a href=&quot;https://www.cloudfest.com/hackathon&quot; rel=&quot;noreferrer noopener&quot;&gt;Cloudfest Hackathon&lt;/a&gt;, where open source enthusiasts join forces with industry partners to work on exciting projects.&lt;/p&gt;


&lt;p&gt;The last two planned editions of this hackathon had to be canceled due to the pandemic, so I was even more eager this time to get together with the other participants and have a few days of social fun in a creative setting.&lt;/p&gt;


&lt;h2&gt;What is Bento?&lt;/h2&gt;


&lt;p&gt;Bento is a relatively new high-performance web components library that makes it easy to optimize your web properties for a great page experience. It is officially governed through the OpenJS Foundation and was initially conceived to make the performance insights and engineering expertise of the AMP project available to more people and with fewer strings attached. Bento components are self-contained and can be used in a gradual mix-and-match approach, as opposed to the all-or-nothing proposition that the AMP runtime tries to enforce.&lt;/p&gt;


&lt;p&gt;Bento components are packaged as &lt;a href=&quot;https://reactjs.org/&quot; rel=&quot;noreferrer noopener&quot;&gt;React&lt;/a&gt; or &lt;a href=&quot;https://preactjs.com/&quot; rel=&quot;noreferrer noopener&quot;&gt;Preact&lt;/a&gt; components for a seamless integration into any framework using such a stack. However, they are also provided as standardized &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/Web_Components&quot; rel=&quot;noreferrer noopener&quot;&gt;Web Components&lt;/a&gt; so that they can be used anywhere else where (P)React might not be available.&lt;/p&gt;


&lt;h2&gt;Why would Bento be a good fit for Gutenberg Blocks?&lt;/h2&gt;


&lt;p&gt;The WordPress block-based editor, or Gutenberg, lets site owners assemble a page layout via &quot;blocks&quot;. These blocks are designed with two different contexts in mind: an interactive editing representation that lets you manipulate the block to your liking within the admin backend, as well as a rendered frontend representation that gets persisted into the database and is shown to visitors.&lt;/p&gt;


&lt;p&gt;This duality, in its simplest form, is represented by the two main functions that each block needs to provide to properly exist within Gutenberg:&lt;/p&gt;


&lt;pre&gt;import { useBlockProps } from &apos;@wordpress/block-editor&apos;;

const blockSettings = {
    apiVersion: 2,

    // The edit function renders the block in its editable representation.
    edit: () =&amp;gt; {
        const blockProps = useBlockProps();

        return &lt;div&gt;Your block in the editor.&lt;/div&gt;;
    },

    // The save function renders the block in its final frontend form.
    save: () =&amp;gt; {
        const blockProps = useBlockProps.save();

        return &lt;div&gt; Your block on the frontend. &lt;/div&gt;;
    };
};&lt;/pre&gt;


&lt;p&gt;The &quot;&lt;strong&gt;Edit&lt;/strong&gt;&quot; context is what the block editor shows within the WordPress admin backend. It is a fully interactive editing environment powered by React. This allows us to use the React version of the Bento web components within the editor. These React components can be intertwined with the Gutenberg React components in seemingly endless and sometimes quite surprising ways.&lt;/p&gt;


&lt;p&gt;The &quot;&lt;strong&gt;Save&lt;/strong&gt;&quot; context is regular frontend markup. This is the snippet of HTML that will be stored in the content as it is persisted to the database. This, on the other hand, is a perfect fit for the web components that Bento can be compiled into. Instead of the markup being a very complex hierarchy of nested divs and other elements to power such a component, it will be the simplest possible representation in the form of a custom HTML element, like &lt;code&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/code&gt;. This has the advantage that fewer internals bleed into the database, making upgrades to the actual components smoother and less expensive.&lt;/p&gt;


&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2022/04/Image-2022-04-08-at-6.18.07-PM-1024x676.jpeg&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;


&lt;h2&gt;Goal of the Hackathon&lt;/h2&gt;


&lt;p&gt;Pascal &amp;amp; I did not have a very well-defined goal when introducing the project, with the following excerpt as the stated goal leading up to the event:&lt;/p&gt;


&lt;blockquote&gt;&lt;p&gt;The goal would be to create a starter template that makes it easy to quickly set up a WordPress website that has excellent Page Experience scores right out of the gate, by powering Gutenberg blocks via a solid Bento components foundation.&lt;/p&gt;&lt;cite&gt;&lt;a href=&quot;https://www.cloudfest.com/project/bento-wordpress&quot; rel=&quot;noreferrer noopener&quot;&gt;https://www.cloudfest.com/project/bento-wordpress&lt;/a&gt;&lt;/cite&gt;&lt;/blockquote&gt;


&lt;p&gt;Once our group was assembled and started discussing the project, though, the team was quick to agree on an approach and a deliverable to target: a landing page for a fictitious hackathon powered by a Gutenberg full-site editing (FSE) theme and custom blocks using Bento components.&lt;/p&gt;


&lt;p&gt;This would force us to have a practical application that we were aiming for, and it allowed us to split up the tasks in a very pragmatic way, letting us work in parallel for most of the hackathon.&lt;/p&gt;


&lt;figure&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2022/04/IMG_3381-1024x422.jpg&quot; alt=&quot;&quot; /&gt;&lt;figcaption&gt;Room full of busy hackathon participants.&lt;/figcaption&gt;&lt;/figure&gt;


&lt;h2&gt;Bento Components that were Implemented&lt;/h2&gt;


&lt;p&gt;Most Bento components were a 1-to-1 mapping into Gutenberg blocks. However, some components required more than one block to make sense in terms of their UX. The following table summarizes what we ended up with during the course of the hackathon.&lt;/p&gt;


&lt;figure&gt;&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;HTML Element(s)&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;&lt;strong&gt;React Component(s)&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;&lt;strong&gt;Block(s)&lt;/strong&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://bentojs.dev/components/bento-accordion/&quot; rel=&quot;noreferrer noopener&quot;&gt;&lt;/a&gt;&lt;/td&gt;&lt;td&gt;BentoAccordion, BentoAccordionSection, BentoAccordionHeader, BentoAccordionContent&lt;/td&gt;&lt;td&gt;bento/accordion, bento/accordion-section&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://bentojs.dev/components/bento-carousel/&quot; rel=&quot;noreferrer noopener&quot;&gt;&lt;/a&gt;&lt;/td&gt;&lt;td&gt;BentoBaseCarousel&lt;/td&gt;&lt;td&gt;bento/carousel&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://bentojs.dev/components/bento-date-countdown/&quot; rel=&quot;noreferrer noopener&quot;&gt;&lt;/a&gt;&lt;/td&gt;&lt;td&gt;BentoDateCountdown&lt;/td&gt;&lt;td&gt;bento/date-countdown, bento/countdown-days, bento/countdown-hours, bento/countdown-minutes, bento/countdown-seconds&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://bentojs.dev/components/bento-fit-text/&quot; rel=&quot;noreferrer noopener&quot;&gt;&lt;/a&gt;&lt;/td&gt;&lt;td&gt;BentoFitText&lt;/td&gt;&lt;td&gt;bento/fit-text&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://bentojs.dev/components/bento-lightbox-gallery/&quot; rel=&quot;noreferrer noopener&quot;&gt;&lt;/a&gt;&lt;/td&gt;&lt;td&gt;-&lt;/td&gt;&lt;td&gt;&lt;em&gt;(filter)&lt;/em&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://bentojs.dev/components/bento-sidebar/&quot; rel=&quot;noreferrer noopener&quot;&gt;&lt;/a&gt;&lt;/td&gt;&lt;td&gt;&lt;em&gt;(template part)&lt;/em&gt;&lt;/td&gt;&lt;td&gt;bento/sidebar&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;https://bentojs.dev/components/bento-social-share/&quot; rel=&quot;noreferrer noopener&quot;&gt;&lt;/a&gt;&lt;/td&gt;&lt;td&gt;BentoSocialShare&lt;/td&gt;&lt;td&gt;bento/social-share&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;tfoot&gt;&lt;tr&gt;&lt;td&gt;&lt;em&gt;&lt;strong&gt;7 Bento components&lt;/strong&gt;&lt;/em&gt;&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;&lt;em&gt;&lt;strong&gt;11 Gutenberg blocks&lt;/strong&gt;&lt;/em&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tfoot&gt;&lt;/table&gt;&lt;/figure&gt;


&lt;p&gt;All of these 11 blocks combine to power the landing page that we created for this fictitious hackathon. Note that we started with a completed empty theme that only had a &lt;code&gt;theme.json&lt;/code&gt; file to start with. This theme was extracted from the end-to-end tests of the Gutenberg source repository.&lt;/p&gt;


&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2022/04/hackathon-landing-page-screenshot.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;


&lt;p&gt;You can see this page for yourself and experiment with the scrolling, the image lazy loading, etc. by heading to the following URL:&lt;/p&gt;


&lt;p&gt;👉&lt;strong&gt; &lt;a href=&quot;https://bit.ly/bento-wp&quot; rel=&quot;noreferrer noopener&quot;&gt;bit.ly/bento-wp&lt;/a&gt; &lt;/strong&gt;👈&lt;/p&gt;


&lt;h2&gt;Example Component: Bento Fit-Text&lt;/h2&gt;


&lt;p&gt;I&apos;ll use one of the simpler components to demonstrate the interactions between Bento and Gutenberg: the &lt;code&gt;&lt;strong&gt;&lt;a href=&quot;https://bentojs.dev/components/bento-fit-text/&quot; rel=&quot;noreferrer noopener&quot;&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/code&gt; component.&lt;/p&gt;


&lt;p&gt;The Fit-Text component provides a way to render arbitrary text into a block container in such a way that it always properly fills its container. It does so by adapting the font size dynamically, within parametrizable minimum and maximum limits.&lt;/p&gt;


&lt;p&gt;To provide a useful user experience, this component did not only require inspector controls to set the minimum and maximum font size and a way to provide the text to show - it also needed a way to configure the height of the container in an intuitive way.&lt;/p&gt;


&lt;figure&gt;&lt;/figure&gt;


&lt;p&gt;To achieve this, we combined the Bento component with a &lt;code&gt;&lt;/code&gt; component to make it typable, and wrapped it in a &lt;code&gt;&lt;/code&gt; to add a draggable height control.&lt;/p&gt;


&lt;pre&gt;&lt;div&gt;
     {
            setLocalHeight((prevHeight) =&amp;gt; prevHeight + delta.height);
        }}
    &amp;gt;
        
            
        
    
&lt;/div&gt;&lt;/pre&gt;


&lt;h2&gt;What were the Findings?&lt;/h2&gt;


&lt;h4&gt;Both Gutenberg and Bento are flexible enough where it matters&lt;/h4&gt;


&lt;p&gt;We ended up with some pretty wild configurations, nesting Gutenberg blocks within Bento components that are nested in Gutenberg blocks...&lt;/p&gt;


&lt;p&gt;We hit a single issue where something was not working as expected for Gutenberg, and &lt;a href=&quot;https://github.com/WordPress/gutenberg/pull/39597&quot; rel=&quot;noreferrer noopener&quot;&gt;a quick patch&lt;/a&gt; resolved that issue promptly.&lt;/p&gt;


&lt;p&gt;Gutenberg had no trouble at all keeping parts or all of the interactivity of the Bento components alive within the live editor.&lt;/p&gt;


&lt;p&gt;Bento on the other hand was happily accepting any Gutenberg blocks within containers like the accordion section.&lt;/p&gt;


&lt;h4&gt;Gutenberg DX is coming together&lt;/h4&gt;


&lt;p&gt;Maybe this was less of a surprise for some of the other members of the team, but for me personally, the developer experience of integrating these Components into new custom blocks was surprisingly good.&lt;/p&gt;


&lt;p&gt;I still have trouble with finding the information I need, given the lack of up-to-date documentation for all of the new and advanced stuff that Gutenberg provides, but in this specific context, that was a non-issue - given we had members of the core Gutenberg team sitting at our table.&lt;/p&gt;


&lt;p&gt;In the end, it was mostly a matter of finding the right React components for each of the expected user experiences and fiddling with the attributes to get them into the right spots. This made it very quick to get a first prototype going for most of these components.&lt;/p&gt;


&lt;h4&gt;Bento interactivity performance is impressive&lt;/h4&gt;


&lt;p&gt;The Bento components are based on years of engineering efforts to optimize for raw performance and hardware acceleration.&lt;/p&gt;


&lt;p&gt;Components that have animated parts are rendered with surprising smoothness, even in the Gutenberg live editor.&lt;/p&gt;


&lt;p&gt;The page we ended up with was not only completely unoptimized, it was also using images we dragged directly from Unsplash into the editor, with the entire thing hosted on a very slow VPS. Given that what you see on the sample page is probably the worst case scenario, we can confidently say that the performance of the Bento components is as good or even better as we hoped.&lt;/p&gt;


&lt;h2&gt;What&apos;s next?&lt;/h2&gt;


&lt;p&gt;The team already discussed next steps and will proceed to add more polish to the current implementations. We&apos;re also discussing what an appropriate structure of the plugin could look like. Do we want to have all blocks in one single plugin? Multiple plugins with individual blocks? How does this tie into the public block library?&lt;/p&gt;


&lt;p&gt;You can keep up-to-date with our latest development efforts for this project at the following URL:&lt;/p&gt;


&lt;p&gt;👉 &lt;a href=&quot;https://bit.ly/bento-wp-repo&quot; rel=&quot;noreferrer noopener&quot;&gt;&lt;strong&gt;bit.ly/bento-wp-repo&lt;/strong&gt;&lt;/a&gt; 👈&lt;/p&gt;


&lt;p&gt;Thanks again to the entire team that worked on this project and invested time and effort into producing a workable solution in such a short time frame! 🎉&lt;/p&gt;


&lt;p&gt;&lt;a href=&quot;https://twitter.com/swissspidy&quot; rel=&quot;noreferrer noopener&quot;&gt;Pascal Birchler&lt;/a&gt; • &lt;a href=&quot;https://twitter.com/schlessera&quot; rel=&quot;noreferrer noopener&quot;&gt;Alain Schlesser&lt;/a&gt;&lt;/p&gt;


&lt;p&gt;&lt;a href=&quot;https://twitter.com/jessicalyschik&quot; rel=&quot;noreferrer noopener&quot;&gt;Jessica Lyschik&lt;/a&gt; • &lt;a href=&quot;https://twitter.com/priethor&quot; rel=&quot;noreferrer noopener&quot;&gt;Héctor Prieto&lt;/a&gt; • &lt;a href=&quot;https://twitter.com/schmitzoide&quot; rel=&quot;noreferrer noopener&quot;&gt;Marcel Schmitz&lt;/a&gt; • &lt;a href=&quot;https://mobile.twitter.com/adamzielin&quot; rel=&quot;noreferrer noopener&quot;&gt;Adam Zieliński&lt;/a&gt; • &lt;a href=&quot;https://mobile.twitter.com/gziolo&quot; rel=&quot;noreferrer noopener&quot;&gt;Greg Ziółkowski&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>The Cost of Contribution</title><link>https://www.alainschlesser.com/thinking/the-cost-of-contribution/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/the-cost-of-contribution/</guid><description>We need to more openly talk about the adverse effects of doing open source contributions in an unsustainable way and destigmatize the money topic.</description><pubDate>Wed, 20 Nov 2019 00:00:00 GMT</pubDate><content:encoded>
&lt;p&gt;&lt;em&gt;The following text is the script for a lightning talk I did at WordCamp US 2019.&lt;/em&gt; &lt;em&gt;I failed to deliver the talk in the way I had planned for various reasons, so I want to give this important topic a second chance in written form.&lt;/em&gt;&lt;/p&gt;


&lt;hr /&gt;


&lt;p&gt;In the summer of 2014 I started work on my first client site using WordPress, as I had just switched careers from government agent to freelance developer. I made heavy use of the WordPress Codex to learn how to solve my problems, and I found it to be vast, detailed ... and often also very bad advice.&lt;/p&gt;


&lt;p&gt;So I thought to myself: I should blog about this and share better practices with other WordPress developers.&lt;/p&gt;


&lt;p&gt;As I fleshed out more of my project, I started to hit bugs in the WordPress Core code. I&apos;m not talking about exotic edge cases, but rather very obvious bugs. As I found out, these bugs were known, already had patches to fix them and were just waiting for these patches to be committed ... for 3 to 8 years or so!&lt;/p&gt;


&lt;p&gt;So I thought to myself: I should contribute to WordPress Core to help fix those bugs in a shorter time frame.&lt;/p&gt;


&lt;p&gt;&lt;em&gt;That way of &quot;slipping&quot; into contribution probably sounds familiar to a lot of you...&lt;/em&gt;&lt;/p&gt;


&lt;p&gt;After a while, I started questioning my choice of the platform, as WordPress was not the development tool I had hoped it would be, mainly because it prioritizes end-users over developers (and for a valid reason). And just when I considered switching, I experienced the one thing that has continued to keep me in this space: the WordPress Community.&lt;/p&gt;


&lt;p&gt;It&apos;s a community full of passioned and inspiring people, and when you come into contact with it for the first time, it can be very intoxicating - I was hooked right away!&lt;/p&gt;


&lt;p&gt;But with time, I noticed more and more that this highly inspiring and addicting environment did have a negative long-term effect on some community members.&lt;/p&gt;


&lt;p&gt;I witnessed stress, anxiety, and burn-outs amongst the contributors, and a lot of churn in general. So I wondered why such a seemingly positive environment and noble common cause could have such a bad outcome for some people.&lt;/p&gt;


&lt;p&gt;I believe that all of this can be traced back to a very simple root cause: &lt;strong&gt;Cost&lt;/strong&gt;.&lt;/p&gt;


&lt;p&gt;Everything we do comes with a cost attached. It is usually the combination of several different costs: the cost of energy for operating our body and mind, the cost of opportunity for not doing something else, the financial cost of travel and accommodation for attending an event, and so on and so forth.&lt;/p&gt;



&lt;p&gt;The best way to cover cost, in general, is &lt;strong&gt;money&lt;/strong&gt;. It is the tool best fit for the job, as it can be easily traded for other resources and is neither intrinsically valuable nor scarce on its own. It is simply an exchange mechanism for offsetting costs against each other in an asynchronous way.&lt;/p&gt;


&lt;p&gt;In open-source projects, a lot of people are not paid for their contributions and don&apos;t receive money for covering their costs.&lt;/p&gt;


&lt;p&gt;What they usually trade instead is &lt;strong&gt;time&lt;/strong&gt;. But time is a much more scarce resource and cannot be amassed or regained.&lt;/p&gt;


&lt;p&gt;And if you overdo this, you&apos;re spending the time that should rather go into your family or your health instead, with devastating long-term effects.&lt;/p&gt;



&lt;p&gt;So why is it that we tend to keep contributing even to the point of hurting ourselves?&lt;/p&gt;


&lt;p&gt;The main driving force behind this is our natural tendency towards prosocial behavior. On one hand, this is ingrained deep within us, as caring for the group means improving the chances of the group for survival - a fundamental evolutionary mechanism.&lt;/p&gt;


&lt;p&gt;But prosocial behavior is also rooted in a principle called reciprocity. There is a hot debate going on for a while now whether true altruism really does exist, but most researchers seem to agree that when we help someone, we ultimately do it for what we get back in return. This can be a direct benefit, like gratitude or recognition, but it can also be a more subconscious reward, like helping as the fastest way to escape an uncomfortable situation, for example.&lt;/p&gt;


&lt;p&gt;Whether we actually decide to help or not is then a matter of doing a subconscious cost-benefit analysis of the situation. Is the return we get from helping more valuable than the cost we need to invest?&lt;/p&gt;


&lt;p&gt;So wouldn&apos;t that mean that we only contribute as long as our return outweighs the cost we invest...? ... that we&apos;d keep ourselves automatically from overdoing it or hurting ourselves...?&lt;/p&gt;


&lt;p&gt;Unfortunately, it&apos;s not that simple and there are many other factors at play.&lt;/p&gt;


&lt;p&gt;When we help, our body produces serotonin, making us happy about what we did, to encourage this behavior (remember the evolution that is at play). This can lead to an addiction that is commonly known as &quot;helper&apos;s high&quot;, where people simply cannot stop helping and do it even to their own detriment, always chasing the next helper&apos;s high.&lt;/p&gt;


&lt;p&gt;There&apos;s another psychological effect that constantly lets us compare ourselves to our social surroundings and derive our self-esteem from how we perceive these social comparisons. Seeing other people contribute motivates us to contribute as well. Seeing other people contribute more than we do motivates us to try even harder to match this.&lt;/p&gt;


&lt;p&gt;Also, within a given group, people tend to strive for conformity, trying to adhere to whatever the social norm seems to be for that group. What&apos;s worse, if no expectation was explicitly set to define this norm, the group members will deduce it from the perceived behavior of the group. This leads to situations where volunteer contributors, besides their regular day job, try to match the output of professional full-time contributors, because that is what they perceive as the norm in Slack. They are unaware of the large majority of people who can only be seen in Slack every few weeks or months.&lt;/p&gt;


&lt;p&gt;Considering all of these psychological factors makes it even more important to talk about sustainability in open source contributions. People need to be aware of the costs involved, and what it means to contribute to something without hurting yourself or your family in the process.&lt;/p&gt;



&lt;p&gt;Let&apos;s work on destigmatizing the money topic in the open-source space, as it is our best bet for making this work sustainably in the long run. It is not heroic or laudable to do too much and burn out, and we all ultimately lose because of it. We don&apos;t need a rotation of martyrs that we churn through. All we need is a constant accumulation of reasonable and sustainable efforts.&lt;/p&gt;



&lt;p&gt;And please, if you have the feeling that someone is doing too much or putting too much pressure on themselves, absolutely do talk to them and try to address the issue. Who knows, maybe they just weren&apos;t aware that they&apos;re chasing the wrong &quot;norm&quot; to conform to...&lt;/p&gt;


&lt;hr /&gt;


&lt;p&gt;&lt;em&gt;Here&apos;s the video recording of the lightning talk as well, but my bad memory made a mess of the delivery, I&apos;m afraid.&lt;/em&gt;&lt;/p&gt;






&lt;hr /&gt;


&lt;p&gt;Featured image credits: &lt;a href=&quot;https://unsplash.com/@aronvisuals&quot;&gt;Aron Visuals on Unsplash&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Application &lt;=&gt; Server Management Protocol (ASMP)</title><link>https://www.alainschlesser.com/thinking/asmp/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/asmp/</guid><description>While I was in Belgrade for  WordCamp Europe , I took part in a meeting of a smaller group of core contributors to discuss the status and future of the  Servehappy pro...</description><pubDate>Mon, 26 Nov 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;While I was in Belgrade for &lt;a href=&quot;https://2018.europe.wordcamp.org/&quot;&gt;WordCamp Europe&lt;/a&gt;, I took part in a meeting of a smaller group of core contributors to discuss the status and future of the &lt;a href=&quot;https://make.wordpress.org/core/features/servehappy/&quot;&gt;Servehappy project&lt;/a&gt;. One topic we discussed was that the ideal end goal, from the end user&apos;s perspective, would be to have an automatic updating mechanism that keeps the entire server automatically up-to-date and secure. While this might be a lofty goal, we wanted to nevertheless look into what would be necessary to make this a reality.&lt;/p&gt;
&lt;p&gt;While we can already automatically update WordPress Core, as well as plugins and themes, we cannot do the same for the components of the WordPress stack that are installed at the server level. There&apos;s currently no standardized protocol for server applications to request information about or changes to the underlying infrastructure. While we have APIs to provision such servers through code, we have no protocol or API to allow the applications that run on them to make changes after the provisioning.&lt;/p&gt;
&lt;p&gt;I hereby suggest creating a communication protocol (tentatively called ASMP) between servers and applications that run on these servers that allows for bidirectional communication so that these two actors can coordinate.&lt;/p&gt;
&lt;h4&gt;Let&apos;s look at a few examples&lt;/h4&gt;
&lt;p&gt;As an example, think about regular users managing a WordPress site. On the WordPress &quot;Server setup&quot; page in the admin backend, the end user would see the current PHP and MySQL versions used by WordPress, as well as potential notifications about available updates.&lt;/p&gt;
&lt;p&gt;The available updates are calculated by querying ASMP about the &lt;code&gt;&apos;php&apos;&lt;/code&gt; and &lt;code&gt;&apos;mysql&apos;&lt;/code&gt; components and then checking the returned ranges of supported versions against its own requirements.&lt;/p&gt;
&lt;p&gt;When the user wants to run such an update, they click the corresponding button, which will have WordPress send an ASMP request to the server to &lt;code&gt;&apos;set&apos;&lt;/code&gt; the version of the &lt;code&gt;&apos;php&apos;&lt;/code&gt; component to the requested version.&lt;/p&gt;
&lt;p&gt;Then WordPress can poll the ASMP state of that request to get updates. It could return states like &lt;code&gt;&apos;queued&apos;&lt;/code&gt;, &lt;code&gt;&apos;in-progress&apos;&lt;/code&gt;, &lt;code&gt;&apos;completed&apos;&lt;/code&gt; or &lt;code&gt;&apos;rejected&apos;&lt;/code&gt;` to let WordPress know how this is moving forward and adapt the user interface to give feedback to the user.&lt;/p&gt;
&lt;p&gt;This would give more control to users, reduce support tickets for hosting providers and indirectly improve version distribution of the server components managed in this way.&lt;/p&gt;
&lt;p&gt;As another example, think about developers that manage their project through a package manager like Composer or NPM. When you provision a server with a &lt;code&gt;composer install&lt;/code&gt; instruction, you could have Composer automatically make requests to the underlying server based on the &lt;code&gt;&quot;require&quot;&lt;/code&gt; statements that define the platform and extension requirements.&lt;/p&gt;
&lt;p&gt;Composer could just as well throw an error when the server is not capable of providing the requested environment, and let the user know which components failed to resolve properly.&lt;/p&gt;
&lt;h4&gt;Guiding principles&lt;/h4&gt;
&lt;p&gt;Planning the ASMP protocol and providing reference implementations should follow a few guiding principles:&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;Applications can only make requests, not force any changes.&lt;/li&gt;
    &lt;li&gt;There is no guaranteed support, servers are free to only provide partial implementations.&lt;/li&gt;
    &lt;li&gt;Requests are asynchronous, they don&apos;t return responses.&lt;/li&gt;
    &lt;li&gt;State and capabilities can be queried, so that user interface and expectations can be adapted to the current server.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These guiding principles still allow for more exotic implementations, like a request to update a given component doing nothing more than creating a support ticket with required details. Hosting providers are free to choose the subset to implement and the specific way to implement it. The implementations can then grow from there and be further automated in time.&lt;/p&gt;
&lt;h4&gt;Technical details&lt;/h4&gt;
&lt;p&gt;The transport to be used could be regular HTTPS, with a server environment variable providing the host to contact for queries and requests. This environment variable would point to &lt;code&gt;localhost&lt;/code&gt; when running on stand-alone servers, but could be deviated to centralized server for hosting providers that have more complex orchestration needs. The server environment should also contain an authentication mechanism, like a token, to make sure queries and requests can only be made from the correct server.&lt;/p&gt;
&lt;p&gt;We should provide a reference implementation based on a common server distribution. This makes sure that it is easy for hosting providers to add support to their hosting and helps keep the experience consistent.&lt;/p&gt;
&lt;p&gt;Also, focusing on building implementations into popular server control panels would accelerate adoption, as all servers managed through a given control panel would automatically inherit the implementation of the ASMP protocol.&lt;/p&gt;
&lt;h4&gt;What&apos;s next?&lt;/h4&gt;
&lt;p&gt;I am in the process of introducing this as a proposal to the Cloudfest Hackathon which will be held on March 23-25, 2019 in Rust, Germany. If this gets accepted, it will probably be an immediate opportunity to collaborate with major hosting/control panel providers to build a working prototype. Anyone who is interested in participating in this endeavor and willing to travel to Germany for the occasion can still &lt;a href=&quot;https://www.cloudfest.com/hackathon&quot;&gt;apply for the hackathon&lt;/a&gt;.&lt;/p&gt;
</content:encoded></item><item><title>Singletons And Shared Instances</title><link>https://www.alainschlesser.com/thinking/singletons-shared-instances/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/singletons-shared-instances/</guid><description>Every once in a while, when discussing software design with fellow developers, the topic of  Singletons  comes up, especially in the context of WordPress development....</description><pubDate>Sat, 08 Jul 2017 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Every once in a while, when discussing software design with fellow developers, the topic of &lt;em&gt;Singletons&lt;/em&gt; comes up, especially in the context of WordPress development. Often times, I try to explain why these should be avoided, even though they are recognized as being a &quot;standard pattern&quot;.&lt;/p&gt;
&lt;p&gt;In this article, I try to go over the reasoning of why the &lt;em&gt;Singleton&lt;/em&gt; should never be used in your code, and what alternative approaches you can use instead to solve the same problems.&lt;/p&gt;
&lt;h3&gt;What is a Singleton?&lt;/h3&gt;
&lt;p&gt;The &lt;em&gt;Singleton&lt;/em&gt; is a software design pattern that has been described in the book &lt;em&gt;&lt;a href=&quot;http://wiki.c2.com/?DesignPatternsBook&quot;&gt;Design Patterns: Elements of Reusable Object-Oriented Software&lt;/a&gt;&lt;/em&gt; by &quot;&lt;a href=&quot;http://wiki.c2.com/?GangOfFour&quot;&gt;the Gang of Four&lt;/a&gt;&quot;, the reference that effectively started the talk about &lt;em&gt;Design Patterns&lt;/em&gt; as a software engineering tool.&lt;/p&gt;
&lt;p&gt;The basic principle is that you want to ensure there can only ever be a single instance of a given class, and you provide a global point of access for it.&lt;/p&gt;
&lt;p&gt;This is really easy to explain and understand, and for most people, the Singleton is the entry drug into the world of &lt;em&gt;Design Patterns&lt;/em&gt;, making it the single most popular pattern.&lt;/p&gt;
&lt;p&gt;So, given its popularity, and given the fact it is part of the reference book and was amongst the first patterns to be described and standardized, how comes that some developers decry it as an &quot;anti-pattern&quot;? Can it really be that bad?&lt;/p&gt;
&lt;p&gt;Yes.&lt;/p&gt;
&lt;p&gt;Yes, it can.&lt;/p&gt;
&lt;h3&gt;But Singletons are useful and necessary!&lt;/h3&gt;
&lt;p&gt;I notice that a lot of people confuse two related concepts, and when they say they need a &lt;em&gt;Singleton&lt;/em&gt;, they actually mean to say they need to &lt;em&gt;share a same instance of an object across different instantiations&lt;/em&gt;. In general, when you instantiate a class, you create a new instance of that class. But for some objects, you want to always use the same, shared instance of that object, no matter where it is being used.&lt;/p&gt;
&lt;p&gt;But the &lt;em&gt;Singleton&lt;/em&gt; is &lt;strong&gt;not&lt;/strong&gt; the proper solution for this.&lt;/p&gt;
&lt;p&gt;The confusion is caused by the fact that a &lt;em&gt;Singleton&lt;/em&gt; actually combines &lt;strong&gt;two responsibilities in one object&lt;/strong&gt;. Imagine having a &lt;em&gt;Singleton&lt;/em&gt; that is being used to establish a connection to the database. Let&apos;s call it (very creatively) &lt;code&gt;DatabaseConnection&lt;/code&gt;. The &lt;em&gt;Singleton&lt;/em&gt; now has the following two main responsibilities:&lt;/p&gt;
&lt;ol&gt;
   &lt;li&gt;Manage the database connection.&lt;/li&gt;
   &lt;li&gt;Manage the instantiations of the &lt;code&gt;DatabaseConnection&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Responsibility 2. is what makes people pick the &lt;em&gt;Singleton&lt;/em&gt;, but this task should actually be the responsibility of a different object.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The problem with a Singleton is not that it is shared, but that it enforces its own instantiation.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;There&apos;s nothing wrong with using a &lt;em&gt;shared instance&lt;/em&gt;. But the object you want to share is not the place to put that restriction into.&lt;/p&gt;
&lt;p&gt;I&apos;ll show some alternative approaches of how to handle this later in the article. But first, I want to discuss what types of problems the &lt;em&gt;Singleton&lt;/em&gt; will cause.&lt;/p&gt;
&lt;h3&gt;Problems with the Singleton Pattern&lt;/h3&gt;
&lt;h4&gt;Singleton vs SOLID&lt;/h4&gt;
&lt;p&gt;First of all, and this might seem to be more of a theoretical and puristic issue than a real problem at first, the &lt;em&gt;Singleton&lt;/em&gt; design pattern breaks most of the &lt;a href=&quot;https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)&quot;&gt;&lt;em&gt;SOLID&lt;/em&gt;&lt;/a&gt; principles.&lt;/p&gt;
&lt;ul&gt;
   &lt;li&gt;&lt;strong&gt;S &lt;/strong&gt;stands for &quot;&lt;em&gt;Single Responsibility Principle&lt;/em&gt;&quot;. It should be obvious that the &lt;em&gt;Singleton&lt;/em&gt; pattern goes against this principle, as already described above.&lt;/li&gt;
   &lt;li&gt;&lt;strong&gt;O&lt;/strong&gt; stands for &quot;&lt;em&gt;Open/Closed Principle&lt;/em&gt;&quot;, meaning that objects should be open for extension but closed for modification. The &lt;em&gt;Singleton&lt;/em&gt; breaks this principle because it controls the point of access, and will only ever return itself, not an extension.&lt;/li&gt;
   &lt;li&gt;&lt;strong&gt;L&lt;/strong&gt; stands for &quot;&lt;em&gt;Liskov Substitution Principle&lt;/em&gt;&quot;, meaning that objects should be replaceable by instances of their subtypes without needing changes to the consuming code. This obviously does not work out for a &lt;em&gt;Singleton&lt;/em&gt;, as the simple fact of having multiple differing versions of an object causes it to not be a &lt;em&gt;Singleton&lt;/em&gt; anymore.&lt;/li&gt;
   &lt;li&gt;&lt;strong&gt;I&lt;/strong&gt; stands for &quot;&lt;em&gt;Interface Segregation Principl&lt;/em&gt;e&quot;, meaning that you should prefer many client-specific interfaces over one general-purpose one. This is the only principle that the &lt;em&gt;Singleton&lt;/em&gt; does not directly break, but only because the &lt;em&gt;Singleton&lt;/em&gt; does not allow for an interface to begin with.&lt;/li&gt;
   &lt;li&gt;&lt;strong&gt;D&lt;/strong&gt; stands for &quot;&lt;em&gt;Dependency Inversion Principle&lt;/em&gt;&quot;, stating that you should depend on abstractions, not concretions. Once again, the Singleton breaks this principle, because you can only ever depend on the very concrete &lt;em&gt;Singleton&lt;/em&gt; instance.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The &lt;em&gt;Singleton&lt;/em&gt; pattern breaks &lt;strong&gt;four out of five&lt;/strong&gt; SOLID principles! It would probably even want to break the fifth as well, if only it was able to have interfaces in the first place...&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The Singleton pattern breaks four out of five SOLID principles!&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It is easy to say that your code does not work or break because of some random theoretical principles. And although my personal experience has shown time and time again that these principles are amongst the most valuable and enduring guidelines you can adhere to in terms of software design, I acknowledge that just stating this as a &quot;fact&quot; will probably not convince a lot of people. We should look at the impact the &lt;em&gt;Singleton&lt;/em&gt; pattern has for your immediate practical reality.&lt;/p&gt;
&lt;h4&gt;Singleton in practical use&lt;/h4&gt;
&lt;p&gt;Here are the more practical drawbacks and issues that a &lt;em&gt;Singleton&lt;/em&gt; brings about:&lt;/p&gt;
&lt;ul&gt;
   &lt;li&gt;You cannot have arguments passed to/injected into the constructor. As the constructor is only actually executed by the first call that hits the &lt;em&gt;Singleton&lt;/em&gt;, and you cannot know in advance, which of the consuming code will be the first one to hit the &lt;em&gt;Singleton&lt;/em&gt;, all consuming code would need to have the exact same set of arguments to pass to the constructor, which is both not practically feasible in most cases, and rather pointless to begin with. As a result, the &lt;em&gt;Singleton&lt;/em&gt; renders the main mechanism of instantiation in OOP languages useless.&lt;/li&gt;
   &lt;li&gt;You cannot mock the &lt;em&gt;Singleton&lt;/em&gt; away when testing other components that make use of it. This makes proper unit tests practically impossible, because you never have a clear isolation of the code you want to test. This problem is not even caused by the actual logic you want to test, but rather by the arbitrary instantiation restriction you wrapped it into.&lt;/li&gt;
   &lt;li&gt;As the Singleton is a globally accessible construct that is always shared across your entire codebase, it defeats any efforts for encapsulation, causing the exact same problems as global variables do. This means that whatever you try to do to get the &lt;em&gt;Singleton&lt;/em&gt; isolated in an encapsulated part of your code, any other external code can cause side effects and produce bugs through this &lt;em&gt;Singleton&lt;/em&gt;. Without proper encapsulation, the very principles of object-oriented programming are diluted.&lt;/li&gt;
   &lt;li&gt;If you ever have your site/app grow to the point where your &lt;code&gt;DatabaseConnection&lt;/code&gt; &lt;em&gt;Singleton&lt;/em&gt; suddenly needs to allow for a second, different database connection nevertheless, you&apos;re in a world of trouble. Your very architecture needs to be revised, and will probably cause large portions of your code to need a complete rewrite.&lt;/li&gt;
   &lt;li&gt;All of the tests you write that make use of your &lt;em&gt;Singleton&lt;/em&gt; in a direct or indirect way cannot be properly reset from one test to the next. They always carry over state through the &lt;em&gt;Singleton&lt;/em&gt;, which can produce weird behavior where your tests depend on the order they are run in or obfuscate actual bugs because of left-over state.&lt;/li&gt;
   &lt;li&gt;They only enforce their singular instantation for the current process space that is valid for the static scope. This means that you&apos;ll run into issues with multi-threading, with multiple processes or with distributed execution. This should hint to the possibility that they are just a faulty concept that simply breaks down as soon as you work in a distributed system.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Alternatives to using a Singleton&lt;/h3&gt;
&lt;p&gt;I don&apos;t want to be the person that decries everything as bad but then fails to provide viable alternatives or preferable approaches. Although I do think that you need to consider your overall architectural design to decide how best to avoid &lt;em&gt;Singletons&lt;/em&gt; in the first place, I can think of a few common use cases in WordPress where the &lt;em&gt;Singleton&lt;/em&gt; can easily be replaced with a mechanism that meets all requirements while avoiding most or all of the drawbacks. But before describing these, I&apos;d like to point out why all of them are only a compromise.&lt;/p&gt;
&lt;p&gt;There is an actual &quot;ideal structure&quot; for dealing with the construction of an app. The theoretical best case is one single instantiation call in the bootstrap code that builds the entire dependency tree of the complete app from the top down. This would work along the lines of this example:&lt;/p&gt;
&lt;ol&gt;
   &lt;li&gt;Instantiate &lt;code&gt;App&lt;/code&gt; (needs &lt;code&gt;Config&lt;/code&gt;, &lt;code&gt;Database&lt;/code&gt;, &lt;code&gt;Controller)&lt;/code&gt;.&lt;/li&gt;
   &lt;li&gt;Instantiate &lt;code&gt;Config&lt;/code&gt; to inject into &lt;code&gt;App&lt;/code&gt;.&lt;/li&gt;
   &lt;li&gt;Instantiate &lt;code&gt;Database&lt;/code&gt; to inject into &lt;code&gt;App&lt;/code&gt;.&lt;/li&gt;
   &lt;li&gt;Instantiate &lt;code&gt;Controller&lt;/code&gt; to inject into &lt;code&gt;App&lt;/code&gt; (needs &lt;code&gt;Router&lt;/code&gt;, &lt;code&gt;Views&lt;/code&gt;).&lt;/li&gt;
   &lt;li&gt;Instantiate &lt;code&gt;Router&lt;/code&gt; to inject into &lt;code&gt;Controller&lt;/code&gt; (needs &lt;code&gt;HTTPMiddleware&lt;/code&gt;).&lt;/li&gt;
   &lt;li&gt;...&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;With a single call, the entire application stack would be built from the top down, injecting the dependencies as needed. The goals with such an approach:&lt;/p&gt;
&lt;ul&gt;
   &lt;li&gt;Every object has an exact list of dependencies it needs, and should only make use of these dependencies. When something breaks, you can easily isolate the responsible code.&lt;/li&gt;
   &lt;li&gt;No tight coupling between any of the objects, all objects rely on interfaces only while using whatever implementations will be injected.&lt;/li&gt;
   &lt;li&gt;No global state. Every individual subtree in the above hierarchy would be properly isolated from the rest, without the developers being able to introduce bugs into module B while making changes to module A.&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;The ideal app construction is a single instantiation call that builds the entire dependency tree.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;However, as good as this might sound, it is just not possible with WordPress code. WordPress does not provide any centralized container or injection mechanism, and each of the plugins/themes are loaded in an isolated way.&lt;/p&gt;
&lt;p&gt;Keep this in mind while we discuss the possible approaches below. The ideal solution, having the entire WordPress stack be instantiated through one centralized injector, is currently out of reach as it would need to be supported by the WordPress Core. All of the approaches below will share some of the same drawbacks in differing degrees, like the fact that they hide dependencies by accessing them directly from within the logic instead of having them be injected.&lt;/p&gt;
&lt;h4&gt;Singleton code&lt;/h4&gt;
&lt;p&gt;Here is the example code for the &lt;em&gt;Singleton&lt;/em&gt; approach that we will use as a base to compare the other approaches to:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Singleton.
final class DatabaseConnection {

   private static $instance;

   private function __construct() {}

   // Call to get a hold of the one true instance.
   public static function get_instance() {
      if ( ! isset( self::$instance ) ) {
         self::$instance = new self();
      }

      return self::$instance;
   }

   // Actual logic code mixed in with the instantiation mechanism.
   public function query( ...$args ) {
      // Execute query and return results.
   }
}

// Consuming code.
$database = DatabaseConnection::get_instance();
$result   = $database-&amp;gt;query( $query );
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I didn&apos;t include all of the implementation details that &lt;em&gt;Singletons&lt;/em&gt; are often loaded with, as they don&apos;t add anything to the theoretical discussion.&lt;/p&gt;
&lt;h4&gt;Using Factories&lt;/h4&gt;
&lt;p&gt;In most cases, the easiest way to defuse your problems with &lt;em&gt;Singletons&lt;/em&gt; is to use the &lt;em&gt;Factory&lt;/em&gt; pattern instead. A &lt;em&gt;Factory&lt;/em&gt; is an object that has the instantiation of objects as its single responsibility. Instead of having a &lt;code&gt;DatabaseConnectionManager&lt;/code&gt; that takes care of its own instantiation via a &lt;code&gt;get_instance()&lt;/code&gt; method, you&apos;ll have a &lt;code&gt;DatabaseConnectionFactory&lt;/code&gt; that can hand out instances of a &lt;code&gt;DatabaseConnection&lt;/code&gt; object. In general, the &lt;em&gt;Factory&lt;/em&gt; would always hand out new instances of a requested object. But it can decide, based on the requested object and the context, whether to hand out new instances or to always share one instance only.&lt;/p&gt;
&lt;p&gt;Regarding the naming, you might think that this looks more like Java code than PHP code, so feel free to stray away from a too strict (and thus lazy) naming convention and name the &lt;em&gt;Factory&lt;/em&gt; in a more straightforward and creative way.&lt;/p&gt;
&lt;p&gt;Example code for the &lt;em&gt;Factory&lt;/em&gt; approach:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Factory.
final class Database {

   public function get_connection(): DatabaseConnection {
      static $connection = null;

      if ( null === $connection ) {
         // You can have arbitrary logic in here to decide what
         // implementation to use.
         $connection = new MySQLDatabaseConnection();
      }

      return $connection;
   }
}

// Interface, so that we can deal with multiple implementations and properly
// mock for testing.
interface DatabaseConnection {

   public function query( ...$args );
}

// The implementation we&apos;re currently using.
final class MySQLDatabaseConnection implements DatabaseConnection {

   public function query( ...$args ) {
      // Execute query and return results.
   }
}

// Consuming code.
$database = ( new Database )-&amp;gt;get_connection();
$result   = $database-&amp;gt;query( $query );
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can see that the consuming code is not more difficult or verbose to write, there&apos;s only a slight nuance to it. We&apos;ve opted to call the &lt;em&gt;Factory&lt;/em&gt; &lt;code&gt;Database&lt;/code&gt; instead of &lt;code&gt;DatabaseConnectionFactory&lt;/code&gt;, as this is part of the API we&apos;re providing, and we always should strive to hit the right balance between logical precision and elegant consiceness.&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;Factory&lt;/em&gt; version above gets rid of pretty much all of the drawbacks we&apos;ve been identifying before, with a small exception:&lt;/p&gt;
&lt;ul&gt;
   &lt;li&gt;Although we&apos;ve removed the tight coupling to the &lt;code&gt;DatabaseConnection&lt;/code&gt; object, we&apos;ve introduced a tight coupling to the new &lt;em&gt;Factory&lt;/em&gt; instead. This is not problematic, as the &lt;em&gt;Factory&lt;/em&gt; is a pure abstraction, and there&apos;s a very low probability that we need to move away from the actual concept of &quot;instantiation&quot; at one point. If that should happen, the entire paradigm of OOP probably needs to be revised.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You&apos;ll probably start wondering now about the fact that we are not able to enforce a single instantiation anymore. Although we always hand out a shared instance of a &lt;code&gt;DatabaseConnection&lt;/code&gt; implementation, anyone can still just do a &lt;code&gt;new MySQLDatabaseConnection()&lt;/code&gt; and thus get access to an additional instance. Yes, that is correct, and that is actually one of the goals of getting away from the &lt;em&gt;Singleton&lt;/em&gt; pattern. It is good to have conventions about always sharing an instance of an object. But enforcing something like this does not provide additional real-world benefits, while making basic requirements like unit testing impossible.&lt;/p&gt;
&lt;h4&gt;Using Static Proxies&lt;/h4&gt;
&lt;p&gt;A &lt;em&gt;Static Proxy&lt;/em&gt; is another design pattern that can be used to get rid of &lt;em&gt;Singletons&lt;/em&gt;. It introduces more tight coupling than the &lt;em&gt;Factory&lt;/em&gt; does, but this coupling is still only tied to an abstraction, not a concrete implementation. The basic principle is that you have a static mapping of the interface, and these static calls are being transparently forwarded to a concrete implementation behind the scenes. As such, there&apos;s no direct coupling to the actual implementation, and the &lt;em&gt;Static Proxy&lt;/em&gt; is free to decide in what ways to pick the actual implementation to use.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Static Proxy.
final class Database {

   public static function get_connection(): DatabaseConnection {
      static $connection = null;

      if ( null === $connection ) {
         // You can have arbitrary logic in here to decide what
         // implementation to use.
         $connection = new MySQLDatabaseConnection();
      }

      return $connection;
   }

   public static function query( ...$args ) {
      // Forward call to actual implementation.
      self::get_connection()-&amp;gt;query( ...$args );
   }
}

// Interface, so that we can deal with multiple implementations and properly
// mock for testing.
interface DatabaseConnection {

   public function query( ...$args );
}

// The implementation we&apos;re currently using.
final class MySQLDatabaseConnection implements DatabaseConnection {

   public function query( ...$args ) {
      // Execute query and return results.
   }
}

// Consuming code.
$result = Database::query( $query );
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As we can see in the consuming code example, the &lt;em&gt;Static Proxy&lt;/em&gt; creates a very short and clear API, with the drawback being that it tightly couples the code to its class signature. If used in the right places, this should not be a real problem, as the tight coupling is still to an abstraction you can directly control, and not to a concrete implementation. You are still able to swap out the specific database code with a different one as you see fit, and our actual implementation is still a completely normal object that can be easily tested.&lt;/p&gt;
&lt;h4&gt;Using the WordPress Plugin API&lt;/h4&gt;
&lt;p&gt;The WordPress Plugin API can also be used to get rid of &lt;em&gt;Singletons&lt;/em&gt;, when they are being used for their capability of providing global access across plugins. This is a mostly clean solution within the constraints of WordPress, with the added caveat that it ties the entire infrastructure and architecture of your code to the WordPress Plugin API. Don&apos;t use this if you intend to reuse your code with different frameworks.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Interface, so that we can deal with multiple implementations and properly
// mock for testing.
interface DatabaseConnection {

   const FILTER = &apos;get_database_connection&apos;;

   public function query( ...$args );
}

// The implementation we&apos;re currently using.
class MySQLDatabaseConnection implements DatabaseConnection {

   public function query( ...$args ) {
      // Execute query and return results.
   }
}

// Initialization code.
$database = new MySQLDatabaseConnection();
add_filter( DatabaseConnection::FILTER, function () use ( $database ) {
   return $database;
} );

// Consuming code.
$database = apply_filters( DatabaseConnection::FILTER );
$result   = $database-&amp;gt;query( $query );
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;One of the main compromises with this code is that your architecture is directly tied to the WordPress Plugin API. If you ever plan to provide your plugin functionality for Drupal sites as well, you&apos;re facing a complete rewrite.&lt;/p&gt;
&lt;p&gt;Another potential issue is that you&apos;re now relying on the timing of the WordPress hooks. This can introduce timing-related bugs, which are often hard to replicate and debug.&lt;/p&gt;
&lt;h4&gt;Using a Service Locator&lt;/h4&gt;
&lt;p&gt;A &lt;em&gt;Service Locator&lt;/em&gt; is one form of an &lt;em&gt;Inversion of Control Container&lt;/em&gt;. You&apos;ll find several references online outing it as an anti-pattern. This is true to some degree, but as we had already discussed above, all of the recommendations here have to be considered as compromises only.&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;Service Locator&lt;/em&gt; is a container that gives you access to &lt;em&gt;Services&lt;/em&gt; that were implemented elsewhere. The container itself is mostly just a collection of instances mapped to identifiers. More elaborate &lt;em&gt;Service Locator&lt;/em&gt; implementations might add features like lazy instantiation or proxy generation to the mix.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Container interface so that we can swap out the Service Locator
// implementation.
interface Container {

   public function has( string $key ): bool;

   public function get( string $key );
}

// Basic implementation of a Service Locator.
class ServiceLocator implements Container {

   protected $services = [];

   public function has( string $key ): bool {
      return array_key_exists( $key, $this-&amp;gt;services );
   }

   public function get( string $key ) {
      $service = $this-&amp;gt;services[ $key ];
      if ( is_callable( $service ) ) {
         $service = $service();
      }

      return $service;
   }

   public function add( string $key, callable $service ) {
      $this-&amp;gt;services[ $key ] = $service;
   }
}

// Interface, so that we can deal with multiple implementations and properly
// mock for testing.
interface DatabaseConnection {

   public function query( ...$args );
}

// The implementation we&apos;re currently using.
class MySQLDatabaseConnection implements DatabaseConnection {

   public function query( ...$args ) {
      // Execute query and return results.
   }
}

// Initialization code.
$services = new ServiceLocator();
$services-&amp;gt;add( &apos;Database&apos;, function () {
   return new MySQLDatabaseConnection();
} );

// Consuming code.
$result = $services-&amp;gt;get( &apos;Database&apos; )-&amp;gt;query( $query );
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you might have guessed in the above example, there&apos;s still the problem of getting a hold of the reference to the &lt;code&gt;$services&lt;/code&gt; instance. This can be solved by combining it with any of the previous three methods.&lt;/p&gt;
&lt;ul&gt;
   &lt;li&gt;Using a &lt;em&gt;Factory&lt;/em&gt;:
&lt;pre&gt;&lt;code&gt;$result = ( new ServiceLocator() )-&amp;gt;get( &apos;Database&apos; )-&amp;gt;query( $query );
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
   &lt;li&gt;Using a &lt;em&gt;Static Proxy&lt;/em&gt;:
&lt;pre&gt;&lt;code&gt;$result = Services::get( &apos;Database&apos; )-&amp;gt;query( $query );
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
   &lt;li&gt;Using the WordPress Plugin API:
&lt;pre&gt;&lt;code&gt;$services = apply_filters( &apos;get_service_locator&apos; );
$result   = $services-&amp;gt;get( &apos;Database&apos; )-&amp;gt;query( $query );
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This leaves us now with the question of whether we should really use the &quot;anti-pattern&quot; &lt;em&gt;Service Locator&lt;/em&gt; to replace the &quot;anti-pattern&quot; &lt;em&gt;Singleton&lt;/em&gt;... The problem with the &lt;em&gt;Service Locator&lt;/em&gt; is that it &quot;hides&quot; dependencies. To explain what this means, you need to think about a code base that actually uses proper constructor injection throughout. In such a codebase, a quick look at the constructor of a given object immediately lets you know which other objects it depends on. If your object has access to a reference to the &lt;em&gt;Service Locator&lt;/em&gt;, you can get around this explicit dependency resolution and fetch a reference (and thus depend on) any other object from within the actual logic. This is what people refer to when they state that the &lt;em&gt;Service Locator&lt;/em&gt; &quot;hides&quot; dependencies.&lt;/p&gt;
&lt;p&gt;However, within the WordPress context, we need to accept that we&apos;re already blocked from an ideal situation from the start. There is no technical possibility of having proper dependency injection throughout the entire codebase. This means that we have to put some compromise into the code either way. The &lt;em&gt;Service Locator&lt;/em&gt;, although not a perfect solution, is a good fit within the such a legacy context, and at least allows you to have these &quot;compromises&quot; be located in one central place, instead of having your entire codebase be riddled with them.&lt;/p&gt;
&lt;h4&gt;Using Dependency Injection&lt;/h4&gt;
&lt;p&gt;If you are only working from within your own plugin and don&apos;t need to provide access to your objects to other plugins, you&apos;re in luck: you can use true dependency injection to get rid of the need to have global access to your dependencies.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Interface, so that we can deal with multiple implementations and properly
// mock for testing.
interface DatabaseConnection {

   public function query( ...$args );
}

// The implementation we&apos;re currently using.
class MySQLDatabaseConnection implements DatabaseConnection {

   public function query( ...$args ) {
      // Execute query and return results.
   }
}

// We&apos;ll have to model the entire plugin to demonstrate this concept.
class Plugin {

   private $database;

   public function __construct( DatabaseConnection $database ) {
      $this-&amp;gt;database = $database;
   }

   public function run() {
      $consumer = new Consumer( $this-&amp;gt;database );
      return $consumer-&amp;gt;do_query();
   }
}

// Consuming code.
// Also modeled as an entire class to demonstrate constructor injection.
class Consumer {

   private $database;

   public function __construct( DatabaseConnection $database ) {
      $this-&amp;gt;database = $database;
   }

   public function do_query() {
      // Here&apos;s the actual consuming code.
      // At this point, it had an arbitrary database connection injected.
      return $this-&amp;gt;database-&amp;gt;query( $query );
   }
}

// Inject dependencies from the bootstrap code through the entire code tree.
$database = new MySQLDatabaseConnection();
$plugin   = new Plugin( $database );
$result   = $plugin-&amp;gt;run();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This looks a bit more involved now, but keep in mind that we had to build a basic version of the entire plugin to demonstrate the dependency injection.&lt;/p&gt;
&lt;p&gt;As we can&apos;t have full dependency injection across the entire app, we can at least have it within the constraints of our own plugin.&lt;/p&gt;
&lt;p&gt;This is an example of doing the actual wiring in a manual way, by explicitly instantiating all dependencies ourselves. In a more complex codebase, you&apos;d want to look into using an auto-wiring &lt;em&gt;Dependency Injector&lt;/em&gt; (a specialized container) that accepts upfront configuration information and that can then recursively instantiate your entire tree in one call.&lt;/p&gt;
&lt;p&gt;Here&apos;s an example of how this wiring would be done with such a &lt;em&gt;Dependency Injector&lt;/em&gt; (given the same classes/interfaces as in the last example):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Let the injector know what implementation to use for resolving the
// DatabaseConnection interface.
$injector-&amp;gt;alias( DatabaseConnection::class, MySQLDatabaseConnection::class );

// Let the injector know it should always return the same shared instance
// for DatabaseConnection requests.
$injector-&amp;gt;share( DatabaseConnection::class );

// Let the injector instantiate the Plugin class, which will cause it to
// recursively traverse all constructors and instantiate objects to
// resolve dependencies.
$plugin = $injector-&amp;gt;make( Plugin::class );
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Combinations&lt;/h4&gt;
&lt;p&gt;For more complex needs that are distributed across several custom and third-party plugins, you should look into combining the above approaches in ways that are adapted to your specific requirements.&lt;/p&gt;
&lt;p&gt;As an example, I&apos;ve been using the following approach with more complex client projects to get closer to the ideal approach I described further above:&lt;/p&gt;
&lt;ul&gt;
   &lt;li&gt;Every plugin is instantiated through a centralized auto-wiring &lt;em&gt;Dependency Injector&lt;/em&gt;.&lt;/li&gt;
   &lt;li&gt;Every plugin is a service provider that can register services with a centralized &lt;em&gt;Service Locator&lt;/em&gt;.&lt;/li&gt;
   &lt;li&gt;Intra-plugin dependencies -&amp;gt; dependency injection.&lt;/li&gt;
   &lt;li&gt;Inter-plugin dependencies -&amp;gt; service location.&lt;/li&gt;
   &lt;li&gt;Third-party dependencies -&amp;gt; virtual services that wrap third-party functionality.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You can read more about this approach and see a recording of a case study talk on the &lt;a href=&quot;/bright-nucleus-architecture/&quot;&gt;Bright Nucleus Architecture&lt;/a&gt; page.&lt;/p&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;As you can see, there are several viable approaches to getting rid of your &lt;em&gt;Singletons&lt;/em&gt;. While none of them are perfect in the WordPress context, they are all preferable to an actual &lt;em&gt;Singleton&lt;/em&gt;, without exception.&lt;/p&gt;
&lt;p&gt;Remember: the problem with &lt;em&gt;Singletons&lt;/em&gt; is not that they are shared, but that they enforce their own instantiation.&lt;/p&gt;
&lt;p&gt;If you think you know of a specific use case where the &lt;em&gt;Singleton&lt;/em&gt; pattern is the only viable solution, please let me know, as I&apos;d love to discuss!&lt;/p&gt;
</content:encoded></item><item><title>OOP-NOOB Series - The Publicity Stunt</title><link>https://www.alainschlesser.com/thinking/oop-noob-series-the-publicity-stunt/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/oop-noob-series-the-publicity-stunt/</guid><description>Having all methods and properties be public defeats the purpose of using OOP in the first place, as most of the benefits depend on encapsulation.</description><pubDate>Wed, 04 Jan 2017 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;em&gt;This article is part of the &lt;a href=&quot;/oop-noob-series-introduction/&quot;&gt;OOP-NOOB Series&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;What Are We Talking About Here?&lt;/h3&gt;
&lt;p&gt;OOP makes use of access modifiers to control the accessibility of methods and properties. This is what allows you to use the concept of encapsulation, so that you have a public interface that consumers of your code can develop against, as well as a private implementation that needs to be treated as a black box from the outside.&lt;/p&gt;
&lt;p&gt;Having all of your methods and properties be public generally defeats the purpose of using OOP in the first place, as most of the benefits depend on the concept of encapsulation in some form or other.&lt;/p&gt;
&lt;h3&gt;How Are Access Modifiers Being Misused&lt;/h3&gt;
&lt;p&gt;There are a few different ways people misuse OOP access modifiers in PHP, some of which are more sneaky than others.&lt;/p&gt;
&lt;h4&gt;Public Offense&lt;/h4&gt;
&lt;p&gt;The most obvious way to pull the &quot;Publicity Stunt&quot; is to have only &lt;code&gt;public&lt;/code&gt; access modifiers all over the place. This results in code like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class PublicOffenseUser {

   public $username;

   public $password_hash;

   public function get_username() {
      return $this-&amp;gt;username;
   }

   public function set_username( $username ) {
      $this-&amp;gt;username = $this-&amp;gt;validate_username( $username );
   }

   public function set_password( $password ) {
   	  $this-&amp;gt;password_hash = password_hash( $password, PASSWORD_DEFAULT );
   }

   public function check_password( $password ) {
   	  return password_verify( $password, $this-&amp;gt;password_hash );
   }

   public function validate_username( $username ) {
      return filter_var(
         trim( $username ),
         FILTER_SANITIZE_ENCODED,
         FILTER_FLAG_STRIP_LOW
      );
   }
}}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Although this does look like a valid class, it does not make sense as an object according to OOP principles.&lt;/p&gt;
&lt;p&gt;First of all, the &lt;code&gt;validate_username()&lt;/code&gt; method should probably not be part of the public interface that is provided to external consumers. This is an implementation detail, and it should be made private so that it can be changed at any time without needing to consider backward compatibility with consumers of that particular code.&lt;/p&gt;
&lt;p&gt;What&apos;s worse though, is that the properties &lt;code&gt;$username&lt;/code&gt; and &lt;code&gt;$password_hash&lt;/code&gt; are public as well. So, even though we have getters and setters that try their best to enforce the consistency and integrity of these properties, any external code can directly change them at will, therefore bypassing all the integrity checks we could put in place. So, how about setting &lt;code&gt;$username&lt;/code&gt; to &lt;code&gt;-1&lt;/code&gt; and &lt;code&gt;$password_hash&lt;/code&gt; to &lt;code&gt;new RuntimeException( &apos;Nonsense&apos; )&lt;/code&gt;? The class will allow it, so the code should need to be able to handle them, right?&lt;/p&gt;
&lt;p&gt;This might have the &lt;code&gt;class&lt;/code&gt; stamp on it, but don&apos;t be deceived! In terms of how it works, it is closer to procedural code than to OOP. We could just as well have arbitrary variables &lt;code&gt;$username&lt;/code&gt; and &lt;code&gt;$password_hash&lt;/code&gt; in whatever scope, and provide procedural helper functions to deal with them.&lt;/p&gt;
&lt;h4&gt;Sins Of Times Past&lt;/h4&gt;
&lt;p&gt;There&apos;s a disguised version of the above code that looks differently, but results in the exact same behaviour:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class SinsOfTimesPastUser {

   var $username;

   var $password_hash;

   function get_username() {
      return $this-&amp;gt;username;
   }

   function set_username( $username ) {
      $this-&amp;gt;username = $this-&amp;gt;validate_username( $username );
   }

   function set_password( $password ) {
   	  $this-&amp;gt;password_hash = password_hash( $password, PASSWORD_DEFAULT );
   }

   function check_password( $password ) {
   	  return password_verify( $password, $this-&amp;gt;password_hash );
   }

   function validate_username( $username ) {
      return filter_var(
         trim( $username ),
         FILTER_SANITIZE_ENCODED,
         FILTER_FLAG_STRIP_LOW
      );
   }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;See, no &lt;code&gt;public&lt;/code&gt; keywords in the code above!&lt;/p&gt;
&lt;p&gt;However, this code behaves exactly as the version before. Why&apos;s that?&lt;/p&gt;
&lt;p&gt;This syntax is actually PHP 4 code, from back when PHP did not yet offer a full OOP model. There were no access modifiers back then, and where you denoted a method with a simple &lt;code&gt;function&lt;/code&gt;, you did the same for properties with &lt;code&gt;var&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;When you use this code in PHP 5, it offers fallbacks for the old syntax, so that old PHP 4 can still work with newer PHP versions. The only way they could provide a smooth migration from PHP 4 code to PHP 5 code was to make both the &lt;code&gt;var&lt;/code&gt; as well as the access-modifier-less &lt;code&gt;function&lt;/code&gt; fall back to being public. So, yes, internally, this is the exact same code than we had in the first example, with the same issues.&lt;/p&gt;
&lt;h4&gt;A Leak Of Its Own&lt;/h4&gt;
&lt;p&gt;There are some code constructs that can be very deceiving in terms of how access to properties is handled. Here&apos;s such an example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class ALeakOfItsOwn {

   public $username;

   public $email;

   public $phone;

   private $password_hash;

   public function set_password( $password ) {
   	  $this-&amp;gt;password_hash = password_hash( $password, PASSWORD_DEFAULT );
   }

   public function check_password( $password ) {
   	  return password_verify( $password, $this-&amp;gt;password_hash );
   }

   public function __call( $method, $arguments ) {
      $prefix = substr( $method, 0, 4 );
      if ( ! in_array( $prefix, [ &apos;get_&apos;, &apos;set_&apos; ], true ) ) {
         return null;
      }

      $property = substr( $method, 4 );
      if ( property_exists( $this, $property ) ) {
         switch( $prefix ) {
            case &apos;get_&apos;:
               return $this-&amp;gt;$property;
            case &apos;set_&apos;:
               $this-&amp;gt;$property = $arguments[0] ?? null;
         }
      }

      return null;
   }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see above, we have made the properties &lt;code&gt;$username&lt;/code&gt;, &lt;code&gt;$email&lt;/code&gt; and &lt;code&gt;$phone&lt;/code&gt; public for easy access (let&apos;s assume we don&apos;t need validation for now). The &lt;code&gt;$password_hash&lt;/code&gt; however is &lt;code&gt;private&lt;/code&gt;, and it comes with a setter and a &quot;checker&quot; method.&lt;/p&gt;
&lt;p&gt;Then, as we are starting to get a bit too clever, we add a magic method to the class that lets it accept arbitrary method calls. The reason we do this is that we want to reduce the boilerplate code for all the getters and setters for the three public properties. So, in essence, we have replaced 6 methods with only one general-purpose one. Nice!&lt;/p&gt;
&lt;p&gt;The problem is that, without necessarily noticing it, we completely disarmed the access modifiers of the class. So, now, even though the &lt;code&gt;$password_hash&lt;/code&gt; is &lt;code&gt;private&lt;/code&gt; and it has no getter, we can still just use &lt;code&gt;get_password_hash()&lt;/code&gt; to get the property directly, as the property is then indirectly accessed from within the class. Worse yet, although we have a &lt;code&gt;set_password()&lt;/code&gt; method that makes sure we properly hash the value first before storing it, we can just use &lt;code&gt;set_password_hash()&lt;/code&gt; to bypass it.&lt;/p&gt;
&lt;p&gt;So, remember that if you use magic methods like &lt;code&gt;__get()&lt;/code&gt;, &lt;code&gt;__set()&lt;/code&gt;, &lt;code&gt;__call()&lt;/code&gt; or &lt;code&gt;__callStatic()&lt;/code&gt;, it&apos;s on you to make sure you that you adhere to all the access modifier restrictions.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;If you use PHP magic methods, it&apos;s on you to enforce access modifier restrictions!&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;Proper Encapsulation&lt;/h3&gt;
&lt;p&gt;Always remember to build your objects in a way that they provide proper encapsulation. Everything that is public is to be considered an &quot;interface&quot;, and must have all of its inputs checked for consistency and integrity. Everything that should not be part of that public interface needs to private or protected. This then allows you to have areas of code that can be assumed to be safe from external changes and only need to be checked for integrity upon entry.&lt;/p&gt;
&lt;p&gt;Here&apos;s an example of how our class should look:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class EncapsulatedUser {

   private $username;

   private $password_hash;

   public function __construct( $username, $password ) {
      $this-&amp;gt;set_username( $username );
      $this-&amp;gt;set_password( $password );
   }

   public function get_username() {
      return $this-&amp;gt;username;
   }

   public function set_username( $username ) {
      $this-&amp;gt;username = $this-&amp;gt;validate_username( $username );
   }

   public function set_password( $password ) {
   	  $this-&amp;gt;password_hash = password_hash( $password, PASSWORD_DEFAULT );
   }

   public function check_password( $password ) {
   	  return password_verify( $password, $this-&amp;gt;password_hash );
   }

   private function validate_username( $username ) {
      return filter_var(
         trim( $username ),
         FILTER_SANITIZE_ENCODED,
         FILTER_FLAG_STRIP_LOW
      );
   }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There&apos;s no uncontrolled way of changing the &lt;code&gt;$username&lt;/code&gt; or &lt;code&gt;$password_hash&lt;/code&gt; properties from outside of the object. So, whatever checks we include in our getters and setters can be assumed to be enforced at all times. The &lt;code&gt;$username&lt;/code&gt; property will never contain an invalid username, and the &lt;code&gt;$password_hash&lt;/code&gt; property will always contain the hash of a password. We directly control the integrity of our object&apos;s internal state, thus reducing the number of potential bugs we can introduce into our system. This is one of the fundamental benefits that OOP offers over procedural code, so make sure you use it to your advantage.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Encapsulation is one of the major benefits of OOP over procedural code, use it!&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;Encapsulation is an important part of OOP. To make full use of it, use both access modifiers as well as other code constructs to control how and when the internal state of your objects can be changed.&lt;/p&gt;
</content:encoded></item><item><title>Meeting The US Community</title><link>https://www.alainschlesser.com/thinking/meeting-us-community/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/meeting-us-community/</guid><description>As I&apos;m writing this, I&apos;m on my way back home from a short trip to Philadelphia. I got to attend the  PostStatus Publish  conference on December 1st, followed by three...</description><pubDate>Tue, 06 Dec 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;As I&apos;m writing this, I&apos;m on my way back home from a short trip to Philadelphia. I got to attend the &lt;a href=&quot;https://poststatus.com/publish/&quot;&gt;PostStatus Publish&lt;/a&gt; conference on December 1st, followed by three days of &lt;a href=&quot;https://2016.us.wordcamp.org/&quot;&gt;WordCamp US&lt;/a&gt;. This was my first opportunity to meet the US WordPress community in their local habitat, and it was a great experience I will fondly look back to. I had not actually planned to attend this particular WordCamp (or travel so far in the immediate future), but rather decided very spontaneously to attend after a discussion with my wife and a look at the flight rates... and I&apos;m glad I did! Here&apos;s a quick summary of the weekend that brought Discussions, Dinosaurs and Dim Sum!&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Discussions, Dinosaurs &amp;amp; Dim Sum - A Tale Of Two (#WordPress) Conferences.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;Traveling In Good Company&lt;/h3&gt;
&lt;p&gt;I was traveling with Alex Frison and Robert Windisch, partners at &lt;a href=&quot;https://inpsyde.com/en/&quot;&gt;Inpsyde&lt;/a&gt;, a German agency providing enterprise-level solutions built on WordPress. During our flight from London to Philly, we actually were able to get some actual work done as well, which made us feel like &quot;digital contortionists&quot; in the cramped seats.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/12/20161130_182053-1024x768.jpg&quot; alt=&quot;digital-contortionists&quot; /&gt;&lt;/p&gt;
&lt;p&gt;We had a lot of fun throughout the trip, and I am sad I had to leave early and couldn&apos;t join them to head over to the &lt;a href=&quot;https://www.meetup.com/Big-Media-WordPress-Meetup/events/235184756/&quot;&gt;BigWP Meetup&lt;/a&gt; in New York.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Pro Tip: When heading to a #WordCamp, check local #Meetups happening at the same time.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;PostStatus Publish&lt;/h3&gt;
&lt;p&gt;The &lt;em&gt;Publish&lt;/em&gt; is a members-only conference for &lt;a href=&quot;https://poststatus.com/&quot;&gt;PostStatus&lt;/a&gt; members that is a more targeted format than a WordCamp. Put simply, whereas WordCamps are in large parts targeting end-users, Publish targets makers and owners.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/12/20161201_092057-1024x768.jpg&quot; alt=&quot;20161201_092057&quot; /&gt;&lt;/p&gt;
&lt;p&gt;There were a lot of very interesting sessions, with topics you would not find at a typical WordCamp. I really do think that WordCamps might be a bit too broad in scope when you&apos;re looking for business value. While not targeting any specific market segment makes them a very inclusive event, it also means that they are not optimized for any of them either, putting the pressure on the attendees to make the experience have a meaningful ROI. So, in that sense, it was kind of a great combination to have both types of conferences in one location during the same week, as you could have the best of both worlds.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Gallery images pending media migration (attachment ids: 715,716,717).&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The sessions were followed by a laid-back reception where the networking took the center stage. Given the fact that the list of attendees was already so targeted, I&apos;m sure that more than one deal has been made during this reception.&lt;/p&gt;
&lt;h3&gt;WordCamp Session Days&lt;/h3&gt;
&lt;p&gt;During the two normal WordCamp session days, I mostly kept to the hallway track. The sessions were in large parts targeted towards end-users and the community aspect, and I was surprised by the relative lack of more technical topics.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/12/20161203_144932-1024x768.jpg&quot; alt=&quot;20161203_144932&quot; /&gt;&lt;/p&gt;
&lt;p&gt;The hallway track allowed me, just as the Publish did the day before, to finally meet a lot of folks that I had interacted with for some time now through digital means, but never met in person up to that point. Meeting in person immediately adds a new dimension to the daily interactions, so I am very glad I had this opportunity. I am grateful for all the people that I could engage with, and am looking forward to the next opportunity!&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The #HallwayTrack is where it&apos;s at!&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;WordCamp After-Party&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;http://www.ansp.org/visit/exhibits/dinosaurs-unearthed/&quot;&gt;Dinosaurs!&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/12/20161203_214517-1024x768.jpg&quot; alt=&quot;20161203_214517&quot; /&gt;&lt;/p&gt;
&lt;h3&gt;WordCamp Contributor Day&lt;/h3&gt;
&lt;p&gt;The Contributor Day allowed me to meet a lot of the Core development team members I hadn&apos;t met before. My main goal was to more properly identify my own role in WordPress Core development. Although I had contributed to Core for the last two releases, I&apos;m am still feeling that I haven&apos;t yet found the right spot to be in for my efforts to return the most value. The discussions with the Core leads have helped me explore a potential approach  that might currently be the best way forward for myself, and there might be an announcement coming in the near future.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/12/20161204_114002-1024x768.jpg&quot; alt=&quot;20161204_114002&quot; /&gt;&lt;/p&gt;
&lt;p&gt;These discussions were the motivation to even make the trip in the first place, and I can happily say that I feel it was worth it, and can only confirm that WordCamp US is the place to be if you want to have access to all the key players involved with the project. It will be hard to argue against attending the next WordCamp US, so I&apos;ll probably have to permanently include this in my conference attendance planning.&lt;/p&gt;
&lt;h3&gt;Peripherals&lt;/h3&gt;
&lt;p&gt;There were lots of opportunities, during and after the scheduled events, for socializing with great food and beverages. I&apos;ve been to some great locations in Philadelphia, and in this context, I would like to thank &lt;a href=&quot;https://inpsyde.com/&quot;&gt;Inpsyde&lt;/a&gt;, &lt;a href=&quot;https://hmn.md/&quot;&gt;Human Made&lt;/a&gt;, &lt;a href=&quot;https://automattic.com/&quot;&gt;Automattic&lt;/a&gt;, &lt;a href=&quot;https://givewp.com/&quot;&gt;GiveWP&lt;/a&gt;, &lt;a href=&quot;https://www.mediatemple.net/&quot;&gt;Media Temple&lt;/a&gt;, &lt;a href=&quot;https://www.godaddy.com/&quot;&gt;GoDaddy&lt;/a&gt; and &lt;a href=&quot;https://envato.com/&quot;&gt;Envato&lt;/a&gt; for their generosity, during both official and inofficial after-parties. I most fondly remember &lt;a href=&quot;http://www.bingbingdimsum.com/about&quot;&gt;Bing Bing Dim Sum&lt;/a&gt;, which combined an original interior, great dim sum and witty WordCampers into a very funny and pleasurable whole.&lt;/p&gt;
&lt;p&gt;I&apos;ll wrap up this article by sharing some impressions from the trip... Enjoy!&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Gallery images pending media migration (attachment ids: 738,739,741,742,743,745,746,747,748,749,751,752,753,754,755,756,757,758,759,760,761,762,763,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785).&lt;/em&gt;&lt;/p&gt;</content:encoded></item><item><title>Project Moiety - A Hypothetical WordPress Roadmap</title><link>https://www.alainschlesser.com/thinking/project-moiety-a-hypothetical-wordpress-roadmap/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/project-moiety-a-hypothetical-wordpress-roadmap/</guid><description>What would it take for WordPress to reach a next big milestone of accounting for 51% of the web? Let&apos;s find out in this hypothetical roadmap!</description><pubDate>Fri, 18 Nov 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Recently on the &lt;a href=&quot;https://poststatus.com/club/&quot;&gt;PostStatus Slack&lt;/a&gt; team, &lt;a href=&quot;https://twitter.com/BrinWilson&quot;&gt;Brin Wilson&lt;/a&gt; started a discussion about what it would hypothetically take for WordPress to get to be installed on 51% of all websites (&lt;a href=&quot;https://w3techs.com/technologies/overview/content_management/all&quot;&gt;it currently sits at about 27% at the time of this writing&lt;/a&gt;):&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/11/Screenshot-2016-11-17-09.07.02-1024x208.png&quot; alt=&quot;Brin Wilson — So WordPress now powers 27% of all websites and seems to be increasing its market share at a rate of about 2% a year. So to get to 51%, at the present rate, that&apos;ll take another twelve years (happening in 2028 then). Is this realistic do you think? Or do you imagine it&apos;ll take more/less time? Or perhaps even never actually get there at all?&quot; /&gt;&lt;/p&gt;
&lt;p&gt;It is an interesting thought experiment, and a lot of interesting points were made during the discussion. &lt;a href=&quot;https://twitter.com/photomatt&quot;&gt;Matt Mullenweg&lt;/a&gt; weighed in on what he would think makes WordPress the &quot;best possible product&quot;:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/11/Screenshot-2016-11-17-09.07.29-1024x115.png&quot; alt=&quot;Matt Mullenweg — market share is a symptom and result, not a goal. it&apos;s a way to measure how much we&apos;ve created the &apos;best possible product&apos;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://twitter.com/helenhousandi&quot;&gt;Helen Hou-Sandí&lt;/a&gt; made an interesting observation about the two different &quot;camps&quot; that seemed to emerge:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/11/Screenshot-2016-11-17-09.08.48-1024x147.png&quot; alt=&quot;Helen Hou-Sandi — I think the gap between &apos;I believe the growth of WP lies in what users of the UI find to be tangible improvements in their workflows&apos; and &apos;I believe the growth of WP lies in its technical underpinnings&apos; is quite interesting&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://twitter.com/WebZenitude&quot;&gt;Franck Frémont&lt;/a&gt; went ahead and wrote up a &lt;a href=&quot;https://www.webzenitude.com/en/ten-step-wordpress-roadmap/&quot;&gt;proposal&lt;/a&gt; for a long-term roadmap for WordPress, and challenged me to do the same from the technical perspective. So here&apos;s my take on what I would think is necessary to get WordPress to account for 51% of the web.&lt;/p&gt;
&lt;h3&gt;Target Audience&lt;/h3&gt;
&lt;p&gt;Before making change suggestions to go on our roadmap, we need to define what audience we are mainly targeting. Given the methodology that is used to measure the market share (&lt;a href=&quot;https://w3techs.com/technologies&quot;&gt;top 10 million websites according to Alexa rankings&lt;/a&gt;), I don&apos;t think that targeting individual end users will amount to major changes in market share anymore.&lt;/p&gt;
&lt;p&gt;I would rather think that big &lt;strong&gt;enterprise clients&lt;/strong&gt; are the next major audience to target. Right now, WordPress is lacking a lot of important features for enterprise clients, and while they might use it here and there for a blog, it is not often used as a full-blown CMS in an enterprise setting.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The next target audience for major growth opportunity for #WordPress are enterprise clients.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;That&apos;s why I suspect the enterprise segment to provide the biggest growth potential and I will target my hypothetical roadmap accordingly.&lt;/p&gt;
&lt;p&gt;Here it is then, my proposal for a long-term WordPress roadmap...&lt;/p&gt;
&lt;h3&gt;0 - Overview&lt;/h3&gt;
&lt;ol&gt;
    &lt;li&gt;&lt;a href=&quot;#technical-requirements&quot;&gt;Technical Requirements&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#release-strategy&quot;&gt;Release Strategy&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#compliance&quot;&gt;Compliance&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#editorial-workflows&quot;&gt;Editorial Workflows&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#integration-interfaces&quot;&gt;Integration Interfaces&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#deployments&quot;&gt;Deployments&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#command-line-control&quot;&gt;Command-line Control&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#certification&quot;&gt;Certification&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#recommended-partners&quot;&gt;Recommended Partners&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#leadership&quot;&gt;Leadership&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;1 - Technical Requirements&lt;/h3&gt;
&lt;p&gt;For WordPress to be able to continually grow, it needs to have tools at its disposal to keep &lt;a href=&quot;https://en.wikipedia.org/wiki/Software_entropy&quot;&gt;Software Entropy&lt;/a&gt; in check.&lt;/p&gt;
&lt;p&gt;Please consider the following two laws from &lt;a href=&quot;https://en.wikipedia.org/wiki/Lehman%27s_laws_of_software_evolution&quot;&gt;Lehman&apos;s Laws of Software Evolution&lt;/a&gt; (paraphrased):&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;The software must be continually adapted or it becomes progressively less useful.&lt;/li&gt;
    &lt;li&gt;When the software is changed, its complexity increases.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This means that WordPress will need to deal with an ever-increasing level of complexity, and following from that, making changes to WordPress gets increasingly difficult and costly (at least in time and effort, if not financially).&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;#WordPress needs to have tools at its disposal to keep Software Entropy in check.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;As WordPress is a procedural codebase with a lot of global state right now, most changes will need you to consider the entire code base (and thus, the entire complexity) at once. Therefore, my first priority would be to refactor the WordPress Core in a way that gets rid of that global state, and allows for complexity to be properly partitioned, so that you can deal with changes and their consequences in smaller subsets of the code without having any impact on the rest of the codebase.&lt;/p&gt;
&lt;p&gt;This is necessary to be able to adapt to small and large requirements changes that the future might bring. What needs to be avoided at all cost is to encounter the next major web revolution without the means to meet its requirements in a timely and satisfactory way. Failing to do so might eventually lead to WordPress just becoming obsolete.&lt;/p&gt;
&lt;p&gt;I have already written about &lt;a href=&quot;/attracting-developers-wordpress/&quot;&gt;what I think needs to be done to make WordPress ready for major changes&lt;/a&gt; in a previous post.&lt;/p&gt;
&lt;p&gt;Apart from these basic technical requirements, I feel that two additional components should be provided by the WordPress Core:&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;strong&gt;Logging subsystem&lt;/strong&gt;, available to all components. Logging is such a vital feature that it ends up being implemented by nearly every substantial plugin and custom solution. Having a centralized solution provided by Core would avoid everyone reinventing the wheel and would allow for a company to route their entire logging efforts through external logging servers.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Message Bus system&lt;/strong&gt;, allowing to decouple processing tasks from the frontend page requests. There are cron jobs right now, but their usefulness is very limited, and they often cause all sorts of issues. Having a message bus system that can optionally be decoupled from the actual WordPress process (using something like RabbitMQ) would avoid having everything under the sun be directly coupled to the web server&apos;s page rendering process.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Both of these can easily be added through custom development right now, but having them be included within Core (at least as an interface and stub, with optional implementations installed separately) would mean they can be used across vendor boundaries. As an example, if there was a central bus system, a product like WooCommerce could create an event &lt;code&gt;ProductAddedToCatalog&lt;/code&gt;, to trigger its own update mechanisms. This would allow third-party extensions to also listen for that Event and trigger their update mechanisms as well. Both would run independently from each other (so one can&apos;t break the other) and wouldn&apos;t be able to slow down the frontend page request (as they would run in a different process and could potentially even run on a different server).&lt;/p&gt;
&lt;h3&gt;2 - Release Strategy&lt;/h3&gt;
&lt;p&gt;WordPress lifecycle management policy should be rethought, so that there are occasional windows of opportunity where breaking changes are allowed and expected, so that there&apos;s a structured way of shedding needless way and getting rid of legacy burden.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;#WordPress lifecycle management needs occasional breaking changes and LTS releases.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The policy should include a long-term release schedule, with occasional long-term support releases (LTS) and recommended migration paths from one of these to the next.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/nodejs/LTS&quot;&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/11/nodejs-release-schedule-1024x543.png&quot; alt=&quot;node.js release schedule chart with normal and LTS releases&quot; width=&quot;960&quot; height=&quot;509&quot; /&gt;&lt;/a&gt; Example: node.js release schedule (click to open node.js LTS schedule page)&lt;/p&gt;
&lt;p&gt;The benefits of such a release strategy are the following:&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;Backward compatibility (BC) needs only be kept up to the most recent LTS release.&lt;/li&gt;
    &lt;li&gt;BC within the version spectrum between two LTS releases can be even more strict than it currently is.&lt;/li&gt;
    &lt;li&gt;Legacy code and thus complexity can be regularly discarded.&lt;/li&gt;
    &lt;li&gt;LTS releases let enterprises integrate the software into their own long-term planning.&lt;/li&gt;
    &lt;li&gt;Maintenance / updates / migrations are foreseeable and plannable.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A proper release strategy is essential for enterprises, where less &quot;agile&quot; processes like 5-year-forecasts are rather the norm. They need to be able to orchestrate deployments across several different software projects in cycles that span years rather than months.&lt;/p&gt;
&lt;h3&gt;3 - Compliance&lt;/h3&gt;
&lt;p&gt;For enterprise clients, controlling compliance is not a &quot;nice-to-have&quot;, it is a basic requirement of doing business. If WordPress intends to be usable in any mission-critical context for larger organizations, it needs robust tools and solutions for implementing and/or supporting regulatory compliance. This could imply changes like subjecting the business content to enforced data retention policies, keeping auditing logs with the content workflows or even having connectors to integrate with over-arching compliance management solutions.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;For enterprise #WordPress, controlling compliance is a basic requirement of doing business.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This is a very complex subject matter, and difficult to get right at an international level (being that most regulations differ from country to country). While having integrated solutions for all compliance-related areas is a lofty goal indeed, a good first step might be to go over something like the guidelines set forth in &lt;a href=&quot;https://www.compliance.idoxgroup.com/en/compliance_consulting/iso19600.html&quot;&gt;ISO 19600&lt;/a&gt; and make sure that none of these recommendations are actively obstructed by WordPress at least.&lt;/p&gt;
&lt;h3&gt;4 - Editorial Workflows&lt;/h3&gt;
&lt;p&gt;Given that WordPress claims to be a full-blown Content Management System (CMS), it is quite alarming that managing content at scale (large team with large volumes of content) is not realistically possible without a combination of plugins and SaaS enhancements. The actual &quot;Management&quot; of the content does not extend much beyond a simple &lt;a href=&quot;https://en.wikipedia.org/wiki/Create,_read,_update_and_delete&quot;&gt;CRUD&lt;/a&gt; interface.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Right now, it is not realistically possible to manage content at scale with OOTB #WordPress UI.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Large content teams need workflows, customizable states, editorial calendars, communication and collaboration tools, notifications, reports, ... In this regard, WordPress better fits the &quot;development framework&quot; drawer rather than the &quot;content management system&quot; drawer, as the management experience out of the box is far from polished.&lt;/p&gt;
&lt;p&gt;I think this should be tackled from a UX perspective first, while completely disregarding the current technical underpinnings. When the ideal workflow has been identified, the implementation requirements for this workflow should inform the development roadmap, to make the perfect workflow &quot;eventually&quot; possible over a series of iterations. The important thing is that a specific goal has been decided that gives direction to all subsequent UI/UX changes. While there&apos;s lots of work being done on the editorial experience, it often seems as a series of random, disjointed spot repairs, rather than a concerted effort.&lt;/p&gt;
&lt;h3&gt;5 - Integration Interfaces&lt;/h3&gt;
&lt;p&gt;Any larger organization already has lots of mission-critical systems in place that are not easily replaced. WordPress should provide the relevant integration interfaces where it makes sense, opening up the possibility to write connectors to the other systems in a reliable and fail-safe way.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;#WordPress needs clear integration points to allow reliable connectors to external systems.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Although there is already the possibility to add functionality through plugins, this often results in solutions that are arbitrarily tacked onto existing functionality, and that break when using several of these in combination.&lt;/p&gt;
&lt;p&gt;For each of the main integration points, there should be a clearly defined interface that makes it possible to add any number of these integrations in a reliable way.&lt;/p&gt;
&lt;p&gt;Here are some examples of such integration points:&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;User authentication, to provide integrated Single Sign-on, letting IT manage users from outside of WP and letting users log in via their fingerprint or other enterprise mechanisms.&lt;/li&gt;
    &lt;li&gt;File management within Media Library, so that IT can attach several externally managed media libraries and document management systems (with correct support for authorization, searching, etc...)&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;6 - Deployments&lt;/h3&gt;
&lt;p&gt;Right now, proper deployments of a WordPress site are only possible with huge amounts of additional efforts. Two main issues need to be solved to allow for more streamlined deployments:&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;Environment-specific data mustn&apos;t be stored within the content database. The content database should be completely agnostic of the current environment it is being used in.&lt;/li&gt;
    &lt;li&gt;The content within the content database must be properly versioned. Currently, given two similar copies of a WordPress content database, it is next to impossible to find out what exact changes have been done in what order.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These issues are the more common nuisances that deployment systems for WordPress have to deal with. Addressing them to allow for straight-forward and reliable deployments would also encourage the use of standardized deployment tools, instead of all the custom WordPress-specific solutions you need to use right now.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;#WordPress needs standardized deployment tools instead of a random collection of custom solutions.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;7 - Command-line Control&lt;/h3&gt;
&lt;p&gt;An enterprise site needs to be scriptable. The IT department does not want to click through the admin screens on a daily basis to address upcoming action items. They want to write scripts that let them control the entire infrastructure as a coherent whole (or at least give it an honest try).&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The IT department wants scripts that let them control the entire infrastructure as a coherent whole.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;There&apos;s already a great project called &lt;a href=&quot;http://wp-cli.org/&quot;&gt;WP-CLI&lt;/a&gt; that allows you to control your WordPress installation through the command-line. However, it has a few inherent short-comings due to the fact that it is an external addition, not part of the WordPress Core.&lt;/p&gt;
&lt;p&gt;Ideally, WordPress would move towards adopting a &lt;a href=&quot;http://fideloper.com/hexagonal-architecture&quot;&gt;hexagonal architecture&lt;/a&gt;, with both user interface and command-line actions having practically the same execution paths. This opens up the opportunity for more advanced command-line antics and consolidates code between both WordPress and WP-CLI. Having the actual logical processes be decoupled from the user interface representation also makes it much easier to change said user interface in the future.&lt;/p&gt;
&lt;h3&gt;8 - Certification&lt;/h3&gt;
&lt;p&gt;Enterprise HR relies on certifications to be able to hire for minimum skill levels. We all know that this is far from ideal, but it is the only way that HR departments without technical expertise can make sure they don&apos;t hire a complete lemon.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Enterprise HR relies on certifications to be able to hire for minimum skill levels.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;There needs to be a network of certification bodies that can ensure that certified developers / implementors / coaches / ... do indeed offer the minimum set of skills that their position would demand. As a bonus, these institutions could also offer &quot;standardized&quot; training as well.&lt;/p&gt;
&lt;p&gt;As nice as it is to &quot;hire for attitude&quot; or similar approaches, your company will be in real trouble if your developers cannot write basic PHP code without copy-pasting from Google results.&lt;/p&gt;
&lt;p&gt;While this will definitely have an impact on the current low barrier of entry of WordPress, I would assume that the enterprise much prefers having gatekeepers to avoid the most obvious abuse of trust.&lt;/p&gt;
&lt;h3&gt;9 - Recommended Partners&lt;/h3&gt;
&lt;p&gt;While the &lt;em&gt;5-minute install&lt;/em&gt; is nice for private end-users, most larger enterprise projects start by getting implementation/integration experts on location to support the in-house IT staff with collecting requirements first. So, they want to see a list of recommended partners from their area to know where to start and whom to contact.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Enterprise IT needs recommended partners to collaborate on large-scale projects.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It is very difficult to do this without introducing bias and unfair advantages that hurt the core philosophies of the WordPress project. This should be governed by an independent non-profit.&lt;/p&gt;
&lt;h3&gt;10 - Leadership&lt;/h3&gt;
&lt;p&gt;I&apos;ve kept the most important one as the final entry. It is the one element that has a direct impact on the success of all the previous points.&lt;/p&gt;
&lt;p&gt;For a group to make a concerted move into a specific direction, there needs to be leadership. Without leadership, movement will be distributed amongst all sorts of different directions and the result will just average out to lose its impact.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;For a group to make a concerted move into a specific direction, there needs to be Leadership.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;If an enterprise client wants to base its 10-year strategy on a specific offering, they need to see that the team behind that offering has a strong vision and a clear direction.&lt;/p&gt;
&lt;p&gt;The Open Source WordPress Community should try to distil true leaders from its huge group of contributors, and encourage them to proactively shape and chase a bigger vision. While we already have several forms of &quot;middle management&quot; at different levels, it seems to me that the overall progress is decided by a random set of actions, rather than a concerted effort.&lt;/p&gt;
&lt;h3&gt;Okay, Where&apos;s The Source?&lt;/h3&gt;
&lt;p&gt;Unfortunately, I don&apos;t have finished source code to share this time... 😜&lt;/p&gt;
&lt;p&gt;All of the above is mostly meant as food for thought. The way the Open Source project has grown and is currently set up certainly makes it difficult (and maybe uncalled for) to have true leadership and an overarching vision. But that is probably &quot;the next frontier&quot; to explore.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;Please put all feedback and expressions of dismay &lt;a href=&quot;#comments&quot;&gt;in the comments below!&lt;/a&gt;&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;
</content:encoded></item><item><title>Using A Config To Write Reusable Code – Part 3</title><link>https://www.alainschlesser.com/thinking/config-files-for-reusable-code-3/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/config-files-for-reusable-code-3/</guid><description>We examine how the example code from the previous article behaves if we use of a Config file to map data from reusable code to project-specific code.</description><pubDate>Tue, 08 Nov 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;em&gt;This is the third part of a series of articles. ( &lt;a href=&quot;/config-files-for-reusable-code/&quot;&gt;&lt;span&gt;&lt;/span&gt; Part 1&lt;/a&gt;, &lt;a href=&quot;/config-files-for-reusable-code-2/&quot;&gt;&lt;span&gt;&lt;/span&gt; Part 2&lt;/a&gt; )&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;So far, we&apos;ve found out that we need to have a clear separation between reusable code and project-specific code, and we identified the &lt;em&gt;Config file&lt;/em&gt; as being a promising tool to map data from one side of this separation to the other. In this third article, we&apos;ll examine what our Settings page example looks like if we do indeed make use of such a Config file.&lt;/p&gt;
&lt;h3&gt;Code Against Interfaces&lt;/h3&gt;
&lt;p&gt;First, we&apos;ll want an interface that we can code against. This is important, as we don&apos;t want all of the rest of our code to be tightly coupled to one very specific implementation of the Config mechanism. Instead, we want to only couple our code to such an interface that provides the basic methods to access the data, and easily allow better and more feature-complete Config implementations to be injected later on.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;interface ConfigInterface {

   /**
    * Check whether the Config has a specific key.
    *
    * @param  string $key The key to check the existence for.
    * @return bool        Whether the specified key exists.
    */
   public function has_key( $key );

   /**
    * Get the value of a specific key.
    *
    * @param  string $key The key to get the value for.
    * @return mixed       Value of the requested key.
    */
   public function get_key( $key );

   /**
    * Get an array with all the keys.
    *
    * @return array Array of config keys.
    */
   public function get_keys();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is a very basic interface and it will be flexible enough for everything we need to do in these examples.&lt;/p&gt;
&lt;h3&gt;Injecting The Config Object&lt;/h3&gt;
&lt;p&gt;The basic principle now is that each reusable class will need a Config file with the configuration data that contains the project-specific bits to be injected. Our &lt;code&gt;Plugin&lt;/code&gt; class that is responsible for instantiating these objects will inject the matching Config into the reusable class&apos; constructor.&lt;/p&gt;
&lt;p&gt;Here&apos;s how that would look like for &lt;a href=&quot;https://github.com/schlessera/better-settings-v1/blob/master/src/Plugin.php#L36-L46&quot;&gt;the method in our &lt;code&gt;Plugin&lt;/code&gt; class that initializes the Settings page and registers it with WordPress&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public function init_settings_page() {
   // Load configuration for the settings page.
   $config = new Config( AS_BETTER_SETTINGS_1_DIR . &apos;config/settings-page.php&apos; );

   // Initialize settings page.
   $settings_page = new SettingsPage( $config );

   // Register the settings page with WordPress.
   add_action( &apos;init&apos;, [ $settings_page, &apos;register&apos; ] );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We instantiate our basic Config implementation (&lt;a href=&quot;https://github.com/schlessera/better-settings-v1/blob/master/src/Config.php&quot;&gt;see it on GitHub&lt;/a&gt;) by telling it where to find the Config file to load, and the inject that Config into the &lt;code&gt;SettingsPage&lt;/code&gt; class.&lt;/p&gt;
&lt;p&gt;This is still a very naïve implementation, as we need to create a separate file for each object we want to configure, and we are still directly coupling our &lt;code&gt;Plugin&lt;/code&gt; class to a specific Config implementation here. We&apos;ll revisit this bit of code in a later article to further refine both the way we instantiate a Config file as well as the way we decide what subset of the configuration data to use.&lt;/p&gt;
&lt;p&gt;Okay, that was all still very easy, now comes the hard part...&lt;/p&gt;
&lt;h3&gt;Structuring Our Config Data&lt;/h3&gt;
&lt;p&gt;Our goal should be to create a reusable class that can transform a properly laid-out Config file into a collection of admin pages and subpages of arbitrary complexity. We don&apos;t want to have a separate class for each page or a separate class for each section. We want to be able to just tell our &lt;code&gt;SettingsPage&lt;/code&gt; class: &quot;Here, this is what I need, go build it!&quot;.&lt;/p&gt;
&lt;p&gt;The way we can achieve this is be destructuring the hierarchy that goes into building such a Settings page and allow our class to iterate over that hierarchy, looping over multiple elements wherever it makes sense. So, let&apos;s stick with our example we had in the previous articles and build a single page with a single section with two fields. This is what our hierarchical structure will look like:&lt;/p&gt;
&lt;pre&gt;admin page
settings
 \--section
     |--field 1
     \--field 2
&lt;/pre&gt;
&lt;p&gt;The admin pages and the settings are only indirectly connected to each other, as you can have any number of pages without ever using settings. This is why we have these two distinct hierarchical roots.&lt;/p&gt;
&lt;p&gt;At each level in this hierarchy, we need to decide whether it makes sense to loop over multiple elements, or whether there&apos;s only ever one possible element at that level. And as it turns out, each level of this structure can indeed be used multiple times. We can have multiple (sub)pages, we can have multiple sets of settings, we can have multiple sections per set of settings and we can have multiple fields per section.&lt;/p&gt;
&lt;p&gt;What we&apos;ll do in our reusable class then is to have one method per level to add a single element for that level. This then allows us to iterate over our Config file and just loop through multiple elements at the same level and pass each individual item to one of these methods.&lt;/p&gt;
&lt;pre&gt;admin page          =&amp;gt;  add_page()
settings            =&amp;gt;  add_setting()
 \--section         =&amp;gt;  add_section()
     |--field 1     =&amp;gt;  add_field()
     \--field 2       &amp;gt; add_field()
&lt;/pre&gt;
&lt;p&gt;As the entire structure then is recursive, we can simply iterate over our entire Config and pass the entire sub-array of the current level to one of these methods.&lt;/p&gt;
&lt;p&gt;Here&apos;s our Config file:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;return [

   // Admin Pages.
   &apos;pages&apos;    =&amp;gt; [
      &apos;as-settings-better-v1&apos; =&amp;gt; [
         &apos;parent_slug&apos; =&amp;gt; MenuPageSlug::SETTINGS,
         &apos;page_title&apos;  =&amp;gt; &apos;as-settings-better-v1&apos;,
         &apos;menu_title&apos;  =&amp;gt; &apos;as-settings-better-v1&apos;,
         &apos;capability&apos;  =&amp;gt; &apos;manage_options&apos;,
         &apos;view&apos;        =&amp;gt; &apos;views/options-page.php&apos;,
      ],
   ],

   // Settings API Settings Group.
   &apos;settings&apos; =&amp;gt; [
      &apos;assb1_settings&apos; =&amp;gt; [

         // Settings API Sections.
         &apos;sections&apos;          =&amp;gt; [
            &apos;assb1_settings_section&apos; =&amp;gt; [
               &apos;view&apos;   =&amp;gt; &apos;views/section-description.php&apos;,

               // Settings API Fields.
               &apos;fields&apos; =&amp;gt; [
                  &apos;assb1_text_field_first_name&apos; =&amp;gt; [
                     &apos;view&apos;  =&amp;gt; &apos;views/first-name-field.php&apos;,
                  ],
                  &apos;assb1_text_field_last_name&apos;  =&amp;gt; [
                     &apos;view&apos;  =&amp;gt; &apos;views/last-name-field.php&apos;,
                  ],
               ],
            ],
         ],
      ],
   ],
];
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is a simplified version of the Config file to make the structure obvious. You can also take a look at the &lt;a href=&quot;https://github.com/schlessera/better-settings-v1/blob/master/config/settings-page.php&quot;&gt;complete Config file with comments&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;I added inline comments to show where our indentation levels map to our overall Settings API hierarchy.&lt;/p&gt;
&lt;p&gt;It should be rather obvious that assembling a Settings page through such a Config file, where we have adapted the way we submit the data to best fit the conceptual structure, is much easier than fooling around with several different WordPress functions, each of which needs a different callback to be able to complete its work.&lt;/p&gt;
&lt;h3&gt;Implementing The Settings Page&lt;/h3&gt;
&lt;p&gt;To make this all work, we will parse this Config file from within our &lt;code&gt;SettingsPage&lt;/code&gt; class and pass all the relevant bits to the corresponding WordPress functions.&lt;/p&gt;
&lt;p&gt;WordPress normally gets a callback for each of its Settings API functions, which is responsible for rendering the corresponding element. However, as we don&apos;t want to deal with random callbacks and markup inside of functions, we map each of these callbacks to a View using a closure.&lt;/p&gt;
&lt;p&gt;Here&apos;s the example of a field being registered with WordPress:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;protected function add_field( $data, $name, $args ) {
   // Prepare the rendering callback.
   $render_callback = function () use ( $data, $args ) {
      if ( ! array_key_exists( &apos;view&apos;, $data ) ) {
         return;
      }

      // Fetch $options to pass into view.
      $options = get_option( $args[&apos;setting_name&apos;] );
      $this-&amp;gt;render_view( $data[&apos;view&apos;], [ &apos;options&apos; =&amp;gt; $options ] );
   };

   add_settings_field(
      $name,
      $data[&apos;title&apos;],
      $render_callback,
      $args[&apos;page&apos;],
      $args[&apos;section&apos;]
   );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;$data&lt;/code&gt; and &lt;code&gt;$name&lt;/code&gt; arguments are passed in by &lt;code&gt;array_walk()&lt;/code&gt; as part of its traversal. We&apos;ve also added a third argument &lt;code&gt;$args&lt;/code&gt; which is an associative array with additional data we need to pass around from level to level.&lt;/p&gt;
&lt;p&gt;We then use these arguments to build a closure called &lt;code&gt;$render_callback&lt;/code&gt;. The closure basically a) makes sure the Config has provided a view to render, b) builds the contextual data for that view and then c) renders the view from within the correct context.&lt;/p&gt;
&lt;p&gt;Then, we call the WordPress function &lt;code&gt;add_settings_field()&lt;/code&gt; with the closure we just built as the callback.&lt;/p&gt;
&lt;p&gt;The developer adding a new Settings page does not need to care about all of this. The only thing that (s)he needs to add is a path to a view (or an instance of one).&lt;/p&gt;
&lt;h3&gt;Yay, Free Code!&lt;/h3&gt;
&lt;p&gt;You can browse or download the source code for this iteration of the plugin from its &lt;a href=&quot;https://github.com/schlessera/better-settings-v1&quot;&gt;GitHub repository&lt;/a&gt;. It should contain lots of comments or hopefully descriptive method names. But if all else fails, do not hesitate to ask questions in the comments section below! This refactoring round added an entire level of abstraction, so I&apos;m not entirely sure my attempts at explaining these changes will be satisfying.&lt;/p&gt;
&lt;p&gt;In the next article of this series (which will be out in the coming days or months), we will completely isolate the different components we&apos;ve now refactored and put them in entirely separate packages.&lt;/p&gt;
</content:encoded></item><item><title>Structuring PHP Exceptions</title><link>https://www.alainschlesser.com/thinking/structuring-php-exceptions/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/structuring-php-exceptions/</guid><description>While the consensus is to use exceptions instead of errors, there is very little information on how to structure and manage them in a larger codebase.</description><pubDate>Mon, 24 Oct 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I seem to constantly work on improving my habits regarding the use of &lt;a href=&quot;http://php.net/manual/en/language.exceptions.php&quot;&gt;exceptions&lt;/a&gt;. I think it is an area that I haven&apos;t yet fully explored, and it is very difficult to find anything more than very basic explanations and tutorials online. While the consensus is to use exceptions, there is very little information on how to structure and manage them &lt;strong&gt;in a larger codebase&lt;/strong&gt;. The larger and more complex your projects become, the more important it is to start with a proper structure to avoid expensive refactoring later on. Your client will surely be thankful!&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;In large #PHP projects, start with a proper structure to avoid expensive refactoring later on.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;In this article, I want to talk about the way I currently set them up and use them in PHP, in the hopes to spark some discussion on the topic and get further feedback.&lt;/p&gt;
&lt;h3&gt;Why Even Use Exceptions?&lt;/h3&gt;
&lt;p&gt;Before discussing implementation details, I think it is necessary to mention what the &lt;strong&gt;main benefit of exceptions&lt;/strong&gt; is when compared to something like &lt;a href=&quot;http://php.net/manual/en/function.trigger-error.php&quot;&gt;&lt;code&gt;trigger_error&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Normal PHP errors and warnings come from the procedural world, and they provide one central mechanism to deal with these errors, a function you declare as being the error handler through the &lt;a href=&quot;http://php.net/manual/en/function.set-error-handler.php&quot;&gt;&lt;code&gt;set_error_handler&lt;/code&gt;&lt;/a&gt; method. Apart from being able to set different error handlers for different levels of errors, you have no further way of controlling the point where you can deal with your errors. The error handler is somewhat outside of the context of you current execution flow, so it is very difficult to do anything meaningful to recover from the error once you&apos;ve reached that point.&lt;/p&gt;
&lt;p&gt;Exceptions, on the other hand, can be dealt with at any point in your code. And, as they escalate throughout your different layers of code, you can decide for each exception at which layer and in which context you want to deal with them. This allows you to catch and gracefully handle exceptions directly in the calling code when this makes sense, and let them bubble to the surface if not.&lt;/p&gt;
&lt;p&gt;As an example, when your code that fetches an entry from the database throws an exception, you can handle this in a nuanced way based on the type of the exception. Did the database not return a result because that ID was not known? Maybe return a &lt;a href=&quot;https://sourcemaking.com/design_patterns/null_object&quot;&gt;&lt;code&gt;NullObject&lt;/code&gt;&lt;/a&gt; instead of throwing an error. This will let a user continue working with the system without getting fatal errors. If the connection could not be established, however, we might want to have our exception bubble up to the infrastructure layer to immediately point to a bigger issue.&lt;/p&gt;
&lt;h3&gt;Build Upon SPL Exceptions&lt;/h3&gt;
&lt;p&gt;The &lt;a href=&quot;http://php.net/manual/en/book.spl.php&quot;&gt;Standard PHP Library (SPL)&lt;/a&gt; provides a &lt;a href=&quot;http://php.net/manual/en/spl.exceptions.php&quot;&gt;predefined set of exceptions&lt;/a&gt; that I would recommend you to build upon. These provide a generalized classification and having your own exceptions extend these makes it easier for consuming code to catch them. The consuming code can, for example, choose to catch the general group of &lt;a href=&quot;http://php.net/manual/en/class.runtimeexception.php&quot;&gt;&lt;code&gt;RuntimeException&lt;/code&gt;&lt;/a&gt;, which would include standard PHP exceptions as well as your own extensions of this.&lt;/p&gt;
&lt;p&gt;For my own components, I have a &lt;a href=&quot;https://github.com/brightnucleus/exceptions&quot;&gt;standard set of exception groupings&lt;/a&gt; I pull in via Composer that mirrors these SPL exceptions while adding an interface to them that is specific to my component&apos;s organization. All of my custom exceptions then extend one of these.The point of adding this additional layer of exceptions is to have one additional way of filtering what exceptions I want to catch. I found this to be needed when you work in a codebase where project code is built on a framework, and that framework is built on individual packages.&lt;/p&gt;
&lt;p&gt;Every base exceptions in that standard set both extends one of the SPL exceptions as well as implements the &lt;a href=&quot;https://github.com/brightnucleus/exceptions/blob/master/src/ExceptionInterface.php&quot;&gt;&lt;code&gt;BrightNucleus\Exception\ExceptionInterface&lt;/code&gt;&lt;/a&gt; interface. This then effectively gives me a way of only catching &quot;Framework-specific&quot; exceptions targeting  from within any of my code, by targeting that interface.&lt;/p&gt;
&lt;p&gt;Here&apos;s a quick summary of how to catch exceptions at different granularities:&lt;/p&gt;
&lt;ol&gt;
    &lt;li&gt;Catch all exceptions
&lt;code&gt;catch( Exception $exception ) {}&lt;/code&gt;&lt;/li&gt;
    &lt;li&gt;Catch all exceptions thrown by a Bright Nucleus library
&lt;code&gt;catch( BrightNucleus\Exception\ExceptionInterface $exception ) {}&lt;/code&gt;&lt;/li&gt;
    &lt;li&gt;Catch a specific SPL exception (BrightNucleus or not)
&lt;code&gt;catch( LogicException $exception )&lt;/code&gt;&lt;/li&gt;
    &lt;li&gt;Catch a specific SPL exception thrown by a Bright Nucleus library
&lt;code&gt;catch( BrightNucleus\Exception\LogicException $exception ) {}&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;As you can see, we cover layer-specific catching as well as type-specific catching with such a structure.&lt;/p&gt;
&lt;h3&gt;Naming Conventions&lt;/h3&gt;
&lt;p&gt;My current take on this is to name the exceptions differently based on whether they represent a specific error to be acted on or a group that other exceptions should extend to further qualify.&lt;/p&gt;
&lt;p&gt;So, as an example, consider having a piece of code that tries to load the contents of a file, and that has three different ways of failing:&lt;/p&gt;
&lt;ol&gt;
    &lt;li&gt;The file name is not valid.&lt;/li&gt;
    &lt;li&gt;The file was not found.&lt;/li&gt;
    &lt;li&gt;The file is not readable.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;I would build the following exceptions to make this semantically clear:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;FileNameWasNotValid extends InvalidArgumentException
FileWasNotFound extends InvalidArgumentException
FileWasNotReadable extends RuntimeException
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The groups have the &lt;code&gt;Exception&lt;/code&gt; suffix, as their naming reflects a &quot;group of exceptions&quot;. The specific exceptions that need to be thrown don&apos;t include that suffix, though, but rather are formed by building a past-tense sentence from the error condition that has happened.&lt;/p&gt;
&lt;p&gt;When exceptions are named in this manner, together with the concept explained in the next sections, reading the code becomes much clearer, as you are almost reading normal sentences.&lt;/p&gt;
&lt;h3&gt;Named Constructors Encapsulate Exception Logic&lt;/h3&gt;
&lt;p&gt;Most developers tend to construct the exceptions right where it happens. This often results in methods where the exception-throwing part actually has more lines of code than the actual logic. Reading code like that is very cumbersome, as you need substantial effort to identify what the important statements are.&lt;/p&gt;
&lt;p&gt;I recommend building named constructors for your exceptions, so that the actual operation of preparing the arguments for instantiating the exception are encapsulated within the exception code, and do not pollute your business logic more than necessary.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Use Named Constructors for your #PHP exceptions to keep your business logic clean.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;As an example, let&apos;s consider this piece of code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public function render( $view ) {

   if ( ! $this-&amp;gt;views-&amp;gt;has( $view ) ) {
      $message = sprintf(
         &apos;The View &quot;%s&quot; does not exist.&apos;,
         json_encode( $view )
      );

      throw new ViewWasNotFound( $message );
   }

   echo $this-&amp;gt;views-&amp;gt;get( $view )-&amp;gt;render();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, the code for dealing with the exception is more complicated than the actual logic. To remedy this, include named constructors in your exceptions, like the following:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class ViewWasNotFound extends InvalidArgumentException {

   public static function fromView( $view, $code = 0, Exception $previous = null ) {
      $message = sprintf(
         &apos;The View &quot;%s&quot; does not exist.&apos;,
         json_encode( $view )
      );

      return new static( $message, $code, $previous );
   }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can have multiple named constructors within the same exception, depending on what context they should be instantiated in. Basically, you&apos;ll have one named constructor for each distinct message.&lt;/p&gt;
&lt;p&gt;Now, rewriting the previous business logic to use this named constructor makes the code much cleaner:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public function render( $view ) {

   if ( ! $this-&amp;gt;views-&amp;gt;has( $view ) ) {
      throw ViewWasNotFound::fromView( $view );
   }

   echo $this-&amp;gt;views-&amp;gt;get( $view )-&amp;gt;render();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Much nicer, don&apos;t you think? Apart from the code being cleaner to read, we&apos;ve also put the actual string to use as message within the Exception itself, which is easier to maintain.&lt;/p&gt;
&lt;h3&gt;Localized Exception Messages&lt;/h3&gt;
&lt;p&gt;In some instances, it might make sense to allow your exception messages to be localized through &lt;code&gt;gettext&lt;/code&gt;. However, I would advise against doing this as a general habit, as it comes with disadvantages as well.&lt;/p&gt;
&lt;p&gt;Localizing the exception messages makes sense for a group of exceptions that is meant to be directly used to provide feedback to the user at the front end.&lt;/p&gt;
&lt;p&gt;Although exceptions should not generally be directly used at the front end (since they should be exceptional, by their very nature), this sometimes might make sense. In such a case, localizing your exceptions is easily done by wrapping the string within your named constructors into &lt;code&gt;gettext&lt;/code&gt; functions.&lt;/p&gt;
&lt;p&gt;The main disadvantage is that exceptions are often searched for through their message string, by developers/sysops in log files, and by users in search engines. Localized messages break such a search strategy. If no other identifier is provided (exception name, exception code), it is very difficult, especially for users, to find out what is going on.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Localized exception messages will make it harder for your users to &apos;google&apos; for solutions.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;Catching Exceptions&lt;/h3&gt;
&lt;p&gt;It sounds very obvious, but it is actually pretty difficult to do in practice: Only catch the exceptions you can directly handle within your current context.&lt;/p&gt;
&lt;p&gt;So, if your intent is to do an operation in a fail-safe way, and return a &lt;code&gt;NullObject&lt;/code&gt; in case something goes south, it is perfectly okay to just generally &lt;code&gt;catch( Exception $exception ) {}&lt;/code&gt;. However, if you are trying to execute an operation that needs to be completed successfully to maintain the integrity of your system, pay close attention to only catch the exceptions that you are actually able to properly remedy. Otherwise, you might prevent a more severe exception to bubble up to the top, and effectively &quot;hiding&quot; an issue within your system.&lt;/p&gt;
&lt;p&gt;In most cases, you should differentiate between logic exceptions and runtime exceptions. That&apos;s why the SPL exceptions we&apos;ve seen before provide these two types as their upper-most level of distinction.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Logic exceptions&lt;/strong&gt; are exceptions where you as a developer are currently doing something wrong. You are asking for values that cannot exist, call methods with the wrong type of argument, etc... This is stuff that needs to be dealt with immediately during development. In a perfect world, a logic exception would never make its way to the production environment.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Logic exceptions should never make their way to your production environment.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;A &lt;strong&gt;runtime exception&lt;/strong&gt;, however, is an error condition that you have no control over during development. A database connection getting blocked by the firewall, a file permission that is incorrect, etc... These errors are unavoidable. You can not &quot;develop a system where the database cannot fail&quot;. What you can do is &quot;develop a system where a failed database connection produces a nice error message and alerts the system administrators, instead of throwing a fatal error&quot;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Your code cannot &apos;never fail&apos;, but it can &apos;only ever fail gracefully&apos;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This is why you should make sure to catch runtime exceptions at some layer in your system (the exact layer depends on many factors), and let logic exceptions pass through so that they throw obvious error messages for the developer.&lt;/p&gt;
&lt;p&gt;Keep in mind that you can provide &lt;strong&gt;multiple catch clauses&lt;/strong&gt;, and an exception will be compared against each of them in order as long as no match was found yet.&lt;/p&gt;
&lt;h3&gt;Central Error Handler&lt;/h3&gt;
&lt;p&gt;To not just take the web server down for the exceptions you let through (whether that was intended or not), you should provide a central error handler that catches any remaining exceptions that haven&apos;t been caught up to that point.&lt;/p&gt;
&lt;p&gt;At the very least, you should log these exceptions and their stack trace, so that you can analyze what has happened after the fact.&lt;/p&gt;
&lt;p&gt;I recommend using something like &lt;a href=&quot;https://github.com/thephpleague/booboo&quot;&gt;BooBoo&lt;/a&gt; to wrap your entire system into such a central error handler.&lt;/p&gt;
&lt;h3&gt;Provide Your Insights&lt;/h3&gt;
&lt;p&gt;This was a quick run-down of how I am currently using exceptions. I don&apos;t think I&apos;ve properly mastered them yet, though. I welcome any feedback or insights on how you use exceptions in your projects and specific issues you&apos;re facing. So please go ahead and &lt;a href=&quot;#comments&quot;&gt;&lt;strong&gt;join the discussion in the comments!&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;strong&gt;Update 2018-07-06&lt;/strong&gt;: Changed the signature of the named constructor to use &lt;code&gt;code = 0&lt;/code&gt; instead of &lt;code&gt;code = null&lt;/code&gt;, to avoid issues with strict type-checking. Kudos to &lt;a href=&quot;https://twitter.com/garyj&quot;&gt;Gary Jones&lt;/a&gt; for the feedback!&lt;/p&gt;
</content:encoded></item><item><title>Interface Naming Conventions</title><link>https://www.alainschlesser.com/thinking/interface-naming-conventions/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/interface-naming-conventions/</guid><description>Naming is an important process that forces you to think about the very nature of things. This article discusses the PHP convention of suffixing interfaces.</description><pubDate>Thu, 20 Oct 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;At an earlier crossing on my development journey, many moons ago, it was considered best practice to use the &quot;&lt;a href=&quot;https://en.wikipedia.org/wiki/Hungarian_notation&quot;&gt;Hungarian Notation&lt;/a&gt;&quot; for variables. You basically prefixed every variable name with a code denoting the data type that variable contained. This resulted in variable names like &lt;code&gt;strName&lt;/code&gt; (a string) or &lt;code&gt;u32Number&lt;/code&gt; (a 32-bit unsigned integer).&lt;/p&gt;
&lt;p&gt;The reason why this was considered best practice was that you were dealing with low-level languages that were pretty literal when given commands by the developer. So, if you had a 32-bit variable, 32 bits of memory were reserved to contain the contents of that variable. If you copied the contents of a different 64-bit variable into that first one, the language would just allow you to do that... writing 32 bits of information into your variable and the remaining 32 bits into whatever happened to be stored immediately behind that allocated spot in the memory. You can be sure that that often resulted in very random bugs, being anything from spectacular to completely undetected until shipped. Take a look at the list of &lt;a href=&quot;https://en.wikipedia.org/wiki/Memory_safety#Types_of_memory_errors&quot;&gt;Types of Memory Errors&lt;/a&gt; for a nice catalog of memory abuse options.&lt;/p&gt;
&lt;p&gt;So, with these languages, it was pretty much necessary to be aware of the exact technical implementations of what you were dealing with, to avoid greater harm. Clean, semantic code was of low priority if it made your computer explode in regular intervals.&lt;/p&gt;
&lt;h3&gt;Rise Of The Garbage (Collector)&lt;/h3&gt;
&lt;p&gt;Nowadays, most people will agree that the benefit of doing so is gone, as we have runtime checks, garbage collectors, and whatnot. That&apos;s why Hungarian Notation is pretty much gone from modern OOP development. You will generally hear that you should code against interfaces, and not against implementations. Your code should not need to know implementation details, as that just causes unwanted coupling.&lt;/p&gt;
&lt;p&gt;In a &lt;a href=&quot;https://en.wikipedia.org/wiki/Type_system#DYNAMIC&quot;&gt;dynamically typed language&lt;/a&gt; like PHP, you are even encouraged to just ignore the type and let the PHP runtime figure it out (&lt;a href=&quot;https://wiki.php.net/rfc/inconsistent-behaviors&quot;&gt;with varying degrees of success&lt;/a&gt;). So, surprisingly, trying to paint three dozen eggs with the following code will just work:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;for( $egg = 1; $egg &amp;lt;= &quot;12 eggs&quot; * &quot;3 dozen&quot;; $egg ++) {
   echo &quot;Painting egg number ${egg}&quot;, PHP_EOL;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, PHP is very &quot;flexible&quot; with its typing system, so there&apos;s no point in distinguishing between a 32-bit and a 64-bit unsigned integer anymore.&lt;/p&gt;
&lt;h3&gt;Code Against Interfaces, Not Implementations&lt;/h3&gt;
&lt;p&gt;One of the most important principles in software development (and one that takes years to properly assimilate) is to always &quot;&lt;strong&gt;code against interfaces, not implementations&lt;/strong&gt;&quot;, with interfaces not referring to the PHP &lt;code&gt;interface&lt;/code&gt; language construct, but rather to the concept of &quot;abstract API that is agnostic of any specific implementation details&quot;.&lt;/p&gt;
&lt;p&gt;The point of this is to decouple every part of your code from the other parts of the code, as well as from any specific, short-lived implementation. For example, if your business logic is expressed entirely in terms of how it interacts with such interfaces, you can replace some or all of your infrastructural implementations without needing to change that business logic.&lt;/p&gt;
&lt;p&gt;When you start really applying this principle consistently, you&apos;ll end up expressing most higher-level logic in terms of how it manipulates the underlying interfaces, and you only ever have interfaces be injected as dependencies.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The logical conclusion should be that this conceptual &quot;interface&quot; then is the most important building block for you to communicate your intent to the system.&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;PSR-2 Suffix To The Rescue...?&lt;/h3&gt;
&lt;p&gt;A lot of developers have trouble thinking in terms of interfaces and APIs. The mind has a natural tendency of thinking procedurally, and you&apos;ll need some time to get good at thinking at the object-oriented level.&lt;/p&gt;
&lt;p&gt;That&apos;s why folks often end up with a number of classes that are just whatever useful first implementation they could come up with.&lt;/p&gt;
&lt;p&gt;When the &lt;a href=&quot;http://www.php-fig.org/&quot;&gt;PHP-FIG&lt;/a&gt; introduced the &lt;a href=&quot;http://www.php-fig.org/psr/psr-2/&quot;&gt;PSR-2 - Coding Style Guide&lt;/a&gt;, they included a &lt;a href=&quot;http://www.php-fig.org/bylaws/psr-naming-conventions/&quot;&gt;bylaw&lt;/a&gt; (which is actually not part of PSR-2) that stated that all interfaces (and this time we&apos;re talking about the actual PHP language construct) should be suffixed with the word &lt;code&gt;Interface&lt;/code&gt; for all code that the PHP-FIG would release. This is why we have a &lt;code&gt;Psr\Log\LoggerInterface&lt;/code&gt; instead of a &lt;code&gt;Psr\Log\Logger&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;This has lead many developers that were still struggling to entirely grasp the OOP paradigm to take a shortcut in their development &quot;proficiency&quot; and let most classes they create implement an interface of the same name, suffixed by the word &lt;code&gt;Interface&lt;/code&gt;. This way, you can &quot;code against an interface&quot; without needing to think about the design of your code. Neat!&lt;/p&gt;
&lt;h3&gt;What&apos;s In A Name?&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Naming a thing is a very important process.&lt;/strong&gt; It forces you to think hard about the actual nature of the thing you want to find a name for. Also, the name brings with it an entire set of assumptions and expectations. If I name a class &lt;code&gt;IconRenderer&lt;/code&gt;, you will probably know not to use that one to make a connection to an FTP server, even without looking up its functionality in the documentation. Similarly, if I name a class &lt;code&gt;Class153A&lt;/code&gt; , you have no clue what that could possibly do.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Naming is an important process that forces you to think about the very nature of things.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;So, the following way of naming classes and interfaces also carries a lot of semantic information:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Thing implements ThingInterface { };
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Because of the way the brain makes assumptions about the logical relation of these two based on the specificity of the words, this tells me loud and clear: &quot;&lt;em&gt;&lt;code&gt;Thing&lt;/code&gt; is what we&apos;re after, that &lt;code&gt;ThingInterface&lt;/code&gt; is only there to support it.&lt;/em&gt;&quot; - &lt;strong&gt;And that&apos;s where we messed with our brain!&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;To properly follow the above-mentioned principle and general best practices, we need to make it obvious for our brain that the interface is what counts, and the actual implementation is just some noisy detail that could easily change from one week to the other:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class CurrentThing implements Thing { };
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So, please take the time to let both of these snippets sink in and consider what their &quot;appearance&quot; suggests. You will probably agree that the &lt;strong&gt;perceived importance&lt;/strong&gt; switches positions from one example to the next.&lt;/p&gt;
&lt;h3&gt;Hungarian Class Notation&lt;/h3&gt;
&lt;p&gt;I see this as a variation of the Hungarian Notation described above. It encodes a technical implementation detail of a given entity into the domain language that we should want to have as clean and clear as possible. And, yes, the word &lt;code&gt;Interface&lt;/code&gt; &lt;strong&gt;is&lt;/strong&gt; an implementation detail, as paradox as that may sound.&lt;/p&gt;
&lt;p&gt;To make this consistent, you would also need to have names like &lt;code&gt;ThingClass&lt;/code&gt; or &lt;code&gt;$thingVariable&lt;/code&gt;. It provides us with information that might be accurate, but &lt;strong&gt;not relevant for the consuming code&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Consider the following code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;?php namespace Example;

use Example\Message;

class MessageRenderer {

   /**
    * @var Message
    */ property $message;

   /**
    * Initialize a Renderer instance.
    *
    * @param Message $message The message we want to render.
    */
   public function __construct( Message $message ) {
      $this-&amp;gt;message = $message;
   }

   /**
    * Render the message.
    */
   public function render() {
      echo $this-&amp;gt;message-&amp;gt;toString();
   }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Is &lt;code&gt;Message&lt;/code&gt; a class?&lt;/p&gt;
&lt;p&gt;Is &lt;code&gt;Message&lt;/code&gt; an interface?&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Should we even care?&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;Yeah, About Naming Being Hard...&lt;/h3&gt;
&lt;p&gt;I would argue that we should get rid of that &lt;code&gt;Interface&lt;/code&gt; suffix and use the most meaningful name for the interface, not the class. &lt;strong&gt;But, what will the class be named then?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If we name our interface &lt;code&gt;Thing&lt;/code&gt;, we need a more qualified name that provides additional information about our specific implementation for the class that implements &lt;code&gt;Thing&lt;/code&gt;. Something like &lt;code&gt;GenericThing&lt;/code&gt; or &lt;code&gt;DefaultThing&lt;/code&gt; does not fit that requirement. Furthermore, it might mean that we will have a situation later on where we need to provide an alternative implementation. Our &lt;code&gt;DefaultThing&lt;/code&gt;  might end up not actually being the &quot;&lt;em&gt;default&lt;/em&gt; thing&quot;.&lt;/p&gt;
&lt;h3&gt;Think About Your Design!&lt;/h3&gt;
&lt;p&gt;You will probably encounter three different situations:&lt;/p&gt;
&lt;ol&gt;
    &lt;li&gt;Your current code needs multiple implementations of a same concept.&lt;/li&gt;
    &lt;li&gt;Your current code provides one implementation of a concept, but is meant to be extended by more specialized third-party code.&lt;/li&gt;
    &lt;li&gt;Your current code only needs a single implementation, and there&apos;s currently no point in extending it.&lt;/li&gt;
&lt;/ol&gt;
&lt;h4&gt;Multiple Implementations Of A Same Concept&lt;/h4&gt;
&lt;p&gt;The first one makes it pretty obvious of how to define the naming. The interface is named after the concept and the actual implementations should be named after what makes it even necessary to have different implementations in the first place. So, as an example, if you need an &lt;code&gt;EmailList&lt;/code&gt; that can work with different mailing list service providers, like MailChimp and AWeber, the names of the classes should reflect that distinction:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;interface EmailList { };

class MailChimpEmailList implements EmailList { };

class AWeberEmailList implements EmailList { };
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;One Implementation Open To Extensions&lt;/h4&gt;
&lt;p&gt;The second situation is less obvious. But generally, the naming should reflect the way you intend the extensions/replacements to happen.&lt;/p&gt;
&lt;p&gt;If the one implementation you provide is useful on its own, you should still name it like you did for the first scenario.&lt;/p&gt;
&lt;p&gt;If the implementation is only meant as a starting point so that the extensions don&apos;t need to start from scratch, you can call it something like &lt;code&gt;BaseThing&lt;/code&gt; and should make it an abstract class.&lt;/p&gt;
&lt;p&gt;If the implementation is just provided so that the code does not throw errors, but does not do anything useful at all, you should name it after the &lt;em&gt;NullObject&lt;/em&gt; pattern: &lt;code&gt;NullThing&lt;/code&gt;.&lt;/p&gt;
&lt;h4&gt;Single Implementation, No Extension Planned&lt;/h4&gt;
&lt;p&gt;This is the most interesting scenario. Most developers will agree that one of the most difficult things to deal with in software development is to correctly anticipate future requirements. In this regard, &quot;not planning to allow extensions&quot; does not necessarily mean that this won&apos;t ever happen or be necessary in the future.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;One of the most difficult things for a developer is to anticipate future requirements.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;If you&apos;re going with the PHP-FIG suffix, you&apos;ll have a &lt;code&gt;ThingInterface&lt;/code&gt; and code that relies upon that interface. Because, introducing a &lt;code&gt;ThingInterface&lt;/code&gt; later on while all your code is programmed against a &lt;code&gt;Thing&lt;/code&gt; would mean major refactoring. This is probably the reason why it is considered a &quot;brainless trend&quot; right now to just provide an interface for everything.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/10/Depositphotos_32551627_original-977x1024.jpg&quot; alt=&quot;Comic about a man wanting to change his name.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;However, that&apos;s where my naming recommendation provides a very nice perk: If your naming does not reflect the difference between interfaces and classes, your code doesn&apos;t need to care!&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Think about it for a second!&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If you don&apos;t plan for your code to be extensible, just go ahead and provide a simple &lt;code&gt;class Thing {};&lt;/code&gt;. As that is not extended, the only places where you&apos;ll encounter it is in type-hints and doc-blocks.&lt;/p&gt;
&lt;p&gt;And after six months, your client might need to have two different &lt;em&gt;things&lt;/em&gt;: one that runs from the database, and one that runs from the filesystem. That&apos;s where the beauty of thoughtful naming comes in... As &lt;code&gt;Thing&lt;/code&gt; still is the actual concept you&apos;re dealing with, you can just turn the class &lt;code&gt;Thing&lt;/code&gt; into an interface without breaking any existing code. And all of your existing code will happily accept that new &lt;code&gt;DatabaseThing implements Thing&lt;/code&gt;, &lt;strong&gt;even though you never planned for that scenario!&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;As a developer, I spend most of my time interacting with the interfaces (in the API sense) that other parts of my code provide. Naming is a hugely important factor to consider and directly influences how effective my work is and how much I enjoy it.&lt;/p&gt;
&lt;p&gt;The names of your objects should directly stem from your domain language and provide a clean representation of it. This will result in code that often is as readable as a normal English prose. The times where we need to add cryptic symbols and abbreviations or encode technical details into our entity names are long gone, and we should be glad about that!&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I would love to hear your thoughts about this! How do you go about naming your interfaces? &lt;a href=&quot;#comments&quot;&gt;Let me know in the comments!&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
</content:encoded></item><item><title>On WordPress And Democracy</title><link>https://www.alainschlesser.com/thinking/on-wordpress-and-democracy/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/on-wordpress-and-democracy/</guid><description>Before you immediately click away, I want to state that this post is not about politics! I want to talk about some of the ideological decisions of the WordPress projec...</description><pubDate>Thu, 15 Sep 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Before you immediately click away, I want to state that this post is not about politics! I want to talk about some of the ideological decisions of the WordPress project and their impact on development. &lt;strong&gt;This is about data and decisions, and about where the former is missing to inform the latter.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;While I&apos;m currently trying to get more involved in contributing to the Core component that makes up WordPress, the system I chose to work with, I feel like seeing a recurring pattern whenever there&apos;s a push for progress. The people in favour of this progress are seen as the &quot;&lt;em&gt;minority&lt;/em&gt;&quot; that does not want to acknowledge what the actual &quot;majority&quot; wants or needs. On the other side, we have people who stand up for this &quot;&lt;em&gt;majority&lt;/em&gt;&quot; and try to defend its position and generally act in its best interest.&lt;/p&gt;
&lt;p&gt;The problem with this is that any knowledge about this &quot;&lt;em&gt;majority&lt;/em&gt;&quot; is mostly just subjective opinion that can neither be verified nor refuted. So, in my eyes, this situation then boils down to one vocal group trying to question the status quo, and their arguments being actually &lt;em&gt;vetoed&lt;/em&gt; by the opposing vocal group using a &quot;&lt;em&gt;majority&lt;/em&gt;&quot; assertion that simply cannot be argued about. This is frustrating for both groups, as the first just feels ignored, and the second will need to re-discuss this topic again and again. The discussion itself will just continue endlessly or slowly fade and dissolve.&lt;/p&gt;
&lt;p&gt;There needs to be a way to resolve such discussions with meaningful data and solid assertions.&lt;/p&gt;
&lt;h3&gt;The WordPress Philosophy&lt;/h3&gt;
&lt;p&gt;Here&apos;s an excerpt from the WordPress Philosophy:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;Design for the Majority&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Many end users of WordPress are non-technically minded. They don’t know what AJAX is, nor do they care about which version of PHP they are using. The average WordPress user simply wants to be able to write without problems or interruption. These are the users that we design the software for as they are ultimately the ones who are going to spend the most time using it for what it was built for.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Here&apos;s another one:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;Clean, Lean, and Mean&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;The core of WordPress will always provide a solid array of basic features. It’s designed to be lean and fast and will always stay that way. We are constantly asked &quot;when will X feature be built&quot; or &quot;why isn’t X plugin integrated into the core&quot;. The rule of thumb is that the core should provide features that 80% or more of end users will actually appreciate and use. If the next version of WordPress comes with a feature that the majority of users immediately want to turn off, or think they’ll never use, then we’ve blown it. If we stick to the 80% principle then this should never happen.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;These principles seem to indicate that all design decisions are ultimately run by the user base to get a kind of &quot;&lt;em&gt;democratic&lt;/em&gt;&quot; voting of what changes to implement or reject. However, the reality is far from that. End users are &quot;&lt;em&gt;belittled&lt;/em&gt;&quot; and only a select group of people gets to define what the &quot;&lt;em&gt;majority&lt;/em&gt;&quot; actually wants.&lt;/p&gt;
&lt;p&gt;There&apos;s also the often referenced mission of WordPress to &quot;democratize publishing&quot;, although this seems to originate from the &lt;a href=&quot;https://wordpress.com/about/&quot;&gt;WordPress.com platform&lt;/a&gt; (although both the &lt;a href=&quot;http://wordpressfoundation.org/&quot;&gt;wordpressfoundation.org&lt;/a&gt; site and several &lt;a href=&quot;https://make.wordpress.org/&quot;&gt;make.wordpress.org&lt;/a&gt; posts seem to indicate that &lt;a href=&quot;http://WordPress.org&quot;&gt;WordPress.org&lt;/a&gt; has accepted this mission as well).&lt;/p&gt;
&lt;h3&gt;Of Wants And Needs&lt;/h3&gt;
&lt;p&gt;My own personal opinion is that most of the time, users (as well as voters) do not really know what is best for them. What they want is not what they need. They are easily manipulated to choose whatever option seems popular, and they don&apos;t have the necessary contextual knowledge to reason about the consequences of their voting.&lt;/p&gt;
&lt;p&gt;Still, I do think that the current situation needs to be addressed, by:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1.) either accepting the democratic notion and introducing a way for users to be included in decision-making;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2) or accepting that there is a need for long-term vision and leadership and providing a process for discussions like the above to be reasonably concluded.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;So, either we go with 1.) and we need to have data about the &quot;&lt;em&gt;majority&lt;/em&gt;&quot; that is used as an argument, or we go with 2.) and the &quot;&lt;em&gt;majority&lt;/em&gt;&quot; has to be dropped as an argument altogether. I would prefer someone telling me &quot;&lt;em&gt;No, we won&apos;t do this, we decided we just don&apos;t want to.&lt;/em&gt;&quot;, rather than coming up with a bogus assertion that just leaves the discussion unresolved. That&apos;s not a productive use of anyone&apos;s time.&lt;/p&gt;
&lt;p&gt;To this end, I have submitted a &lt;a href=&quot;https://core.trac.wordpress.org/ticket/38064&quot;&gt;new Trac ticket&lt;/a&gt; in the hopes we can discuss the merits of directly letting users impact decisions. The goal is to turn the unverifiable &quot;&lt;em&gt;majority&lt;/em&gt;&quot; argument into a valid assertion backed by data.&lt;/p&gt;
&lt;p&gt;I personally would still prefer option 2.) above, as I think it would provide more focused and effective progress, but I strongly doubt that the community can agree on this if we don&apos;t even have the tools for 1.) yet.&lt;/p&gt;
&lt;h3&gt;Now, Where Did That Come From?&lt;/h3&gt;
&lt;p&gt;The impulse to create this ticket was the result of a discussion about &lt;a href=&quot;https://core.trac.wordpress.org/ticket/36335&quot;&gt;introducing an autoloading mechanism into WordPress Core&lt;/a&gt;. This is a hotly debated topic, and some of the arguments were along the lines of &quot;People using XYZ are the minority&quot;, &quot;This is an edge case&quot;, etc...&lt;/p&gt;
&lt;p&gt;As I cannot directly speak on behalf of the &quot;majority&quot;, I launched a Twitter poll to collect data:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://twitter.com/schlessera/status/773178479953272834&quot;&gt;https://twitter.com/schlessera/status/773178479953272834&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Of course, when I posted this data, it was quickly dismissed as not being representative and not having a large enough sample size, and rightfully so!&lt;/p&gt;
&lt;p&gt;However, there&apos;s currently no way I&apos;m aware of to get better data on such topics that would be statistically conclusive. That&apos;s why I think there&apos;s something missing here.&lt;/p&gt;
&lt;h3&gt;Ideological Nonsense?&lt;/h3&gt;
&lt;p&gt;What do you say? Did I drink the wrong coffee this morning, or are there other people who feel the same way? &lt;a href=&quot;#comments&quot;&gt;&lt;strong&gt;Let me know in the comments below either way!&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Two WordPremieres For Me</title><link>https://www.alainschlesser.com/thinking/two-wordpremieres-for-me/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/two-wordpremieres-for-me/</guid><description>This weekend gave me the occasion to add two new activities to my &quot; Done &quot; list: It was both my first volunteering experience and my first speaker gig at a WordCamp. I...</description><pubDate>Tue, 06 Sep 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;This weekend gave me the occasion to add two new activities to my &quot;&lt;em&gt;Done&lt;/em&gt;&quot; list: It was both my first volunteering experience and my first speaker gig at a WordCamp. I&apos;d like to collect some of my experiences here, mostly for myself to not let them fade away with time.&lt;/p&gt;
&lt;h3&gt;Volunteering&lt;/h3&gt;
&lt;p&gt;I had dragged my wife Carole along to &lt;a href=&quot;https://2016.europe.wordcamp.org/&quot;&gt;WordCamp Europe in Vienna this year&lt;/a&gt;, as the city is beautiful, and we prolonged our stay for it to be half-WordCamp, half-QualityTime. She was very anxious about it and expected to be surrounded by nerds making binary jokes and exclusively talking about source code. No matter how often I assured her that WordCamps are not just about web development, she couldn&apos;t imagine how she would fit in with the crowd she imagined to be there.&lt;/p&gt;
&lt;p&gt;As it turns out, she actually fell in love with the community during these few days and, once we were back at home, she immediately started looking for other WordCamps to relive that &quot;energizing and inspiring&quot; experience. That&apos;s when we decided to apply as volunteers together. The first WordCamp that was available for us to apply as volunteers was &lt;a href=&quot;https://2016.frankfurt.wordcamp.org/&quot;&gt;WordCamp Frankfurt&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://twitter.com/schlessera/status/772411090672156672&quot;&gt;https://twitter.com/schlessera/status/772411090672156672&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;I took over some slots to manage one of the auditoriums, while my wife helped take care of the hello station. As our dog-sitter had to cancel at short notice, we even took along three additional volunteers, our dogs Jasper, Duke and Indra, who took care of the general happiness of the attendees.&lt;/p&gt;
&lt;figure&gt;
&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/09/14231215_10210806443503907_1753040331413062543_o-1024x1024.jpg&quot; alt=&quot;My wife Carole and me, with our dogs Jasper, Duke and Indra, in front of a WordCamp Frankfurt poster.&quot; width=&quot;960&quot; height=&quot;960&quot; /&gt;
&lt;figcaption&gt;Photo by &lt;a href=&quot;https://florianziegler.com/&quot;&gt;Florian Ziegler&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Volunteering is a sure-fire way of immediately getting to know great people investing time in doing great stuff. And, if you want to participate in such an event, but are not of the networking type, just apply as a volunteer. You won&apos;t need to go through any extra efforts to meet new people, and you will have specific tasks that give a purpose to your presence. If you still hesitate, just go for it! I promise you won&apos;t regret it.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Volunteering is a sure-fire way of getting to know great people investing time in doing great stuff.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;For a detailed account (in German!) of how our dogs experienced the volunteering work, refer to &lt;a href=&quot;https://afrenchiestale.com/2016/09/05/schniewies-go-wordcamp-frankfurt/&quot;&gt;their latest blog post&lt;/a&gt;!&lt;em&gt; (&lt;a href=&quot;https://translate.google.com/translate?hl=en&amp;amp;sl=de&amp;amp;tl=en&amp;amp;u=https%3A%2F%2Fafrenchiestale.com%2F2016%2F09%2F05%2Fschniewies-go-wordcamp-frankfurt%2F&quot;&gt;In English as translated by Google&lt;/a&gt;)&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;Speaking&lt;/h3&gt;
&lt;p&gt;I had also submitted a proposal as a speaker. My session was called: &quot;&lt;a href=&quot;https://2016.frankfurt.wordcamp.org/session/the-secret-sauce-for-writing-reusable-code/&quot;&gt;The Secret Of Writing Reusable Code&lt;/a&gt;&quot;, and is a more streamlined version of the &lt;a href=&quot;/config-files-for-reusable-code/&quot;&gt;series of blog posts about Config files&lt;/a&gt; I have been doing on this site.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/09/IMG_8372-1024x658.jpg&quot; alt=&quot;Me speaking in front of WordCamp Frankfurt audience&quot; /&gt;&lt;/p&gt;
&lt;p&gt;I had &lt;a href=&quot;/simple-examples-complex-concepts/&quot;&gt;trouble putting my thoughts into tiny slides&lt;/a&gt;, and couldn&apos;t think of meaningful code examples that would fit the format. I had planned on doing a lot of rehearsing to make sure I don&apos;t stumble over the language barrier, as writing a foreign language is nothing compared to speaking it fluently under pressure. In the end, I did not do any rehearsing at all due to becoming frustrated with the slide-writing process, and I just decided to wing it once I&apos;m in front of the audience.&lt;/p&gt;
&lt;p&gt;I did have a bit of trouble starting the talk, but once I managed to get into the flow, I think it all turned out to be easier than I had anticipated. I started to actually enjoy being able to talk about concepts I am passionate about to an interested (hopefully) audience.&lt;/p&gt;
&lt;figure&gt;
&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/09/29446087756_b4f313e9f3_o-1024x682.jpg&quot; alt=&quot;Me passionately explaining a new concept&quot; width=&quot;960&quot; height=&quot;639&quot; /&gt;
&lt;figcaption&gt;Photo by &lt;a href=&quot;https://florianziegler.com/&quot;&gt;Florian Ziegler&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Some of the feedback I got from the (German) audience:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://twitter.com/LMWA360/status/772432348721909762&quot;&gt;https://twitter.com/LMWA360/status/772432348721909762&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://twitter.com/ScreamingDev/status/772433062617579520&quot;&gt;https://twitter.com/ScreamingDev/status/772433062617579520&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://twitter.com/jolutionDE/status/772435410983288832&quot;&gt;https://twitter.com/jolutionDE/status/772435410983288832&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;Slides&lt;/h3&gt;
&lt;p&gt;Here are the slides for the talk. In case you couldn&apos;t attend the session, I would recommend waiting for the &lt;a href=&quot;http://WordPress.TV&quot;&gt;WordPress.TV&lt;/a&gt; video to be published, though. The slides will probably not be very clear in isolation. I will update this post to link to the video as soon as it is available.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://speakerdeck.com/schlessera/the-secret-sauce-for-writing-reusable-code&quot;&gt;https://speakerdeck.com/schlessera/the-secret-sauce-for-writing-reusable-code&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;Video Recording&lt;/h3&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;UPDATE:&lt;/strong&gt;&lt;/em&gt; Here&apos;s the recorded video of the presentation. It seems to confirm that I really did have trouble getting into the presentation in the beginning. Oh well... maybe next time I&apos;ll manage to prepare and rehearse as well.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://wordpress.tv/2016/09/12/alain-schlesser-the-secret-sauce-for-writing-reusable-code/&quot;&gt;http://wordpress.tv/2016/09/12/alain-schlesser-the-secret-sauce-for-writing-reusable-code/&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;Call To Action&lt;/h3&gt;
&lt;p&gt;Yes, normally I try to end every blog post with a call to action, to get you folks out there to comment or subscribe to my updates. However, this time, my call to action is a different one:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://central.wordcamp.org/schedule/&quot;&gt;Find the nearest upcoming WordCamp and apply as a volunteer!&lt;/a&gt;&lt;/p&gt;</content:encoded></item><item><title>Using A Config To Write Reusable Code - Part 2</title><link>https://www.alainschlesser.com/thinking/config-files-for-reusable-code-2/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/config-files-for-reusable-code-2/</guid><description>This is the second part of a series of articles. (     Part 1 ,     Part 3 )</description><pubDate>Wed, 31 Aug 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;em&gt;This is the second part of a series of articles. ( &lt;a href=&quot;/config-files-for-reusable-code/&quot;&gt;&lt;span&gt;&lt;/span&gt; Part 1&lt;/a&gt;, &lt;a href=&quot;/config-files-for-reusable-code-3/&quot;&gt;&lt;span&gt;&lt;/span&gt; Part 3 )&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;In the first part of this series, we&apos;ve seen a simple &quot;OOP&quot; implementation of a &lt;code&gt;SettingsPage&lt;/code&gt;  class that adds a basic settings page to the WordPress admin backend using the Settings API. We&apos;ve also seen that the simple fact of writing OOP code does not in and of itself make the code reusable.&lt;/p&gt;
&lt;p&gt;The goal we identified is that we want to separate project-specific code from reusable code. To be able to put the reusable code into a reusable form, it mustn&apos;t contain any project-specific logic whatsoever.&lt;/p&gt;
&lt;h3&gt;Extracting The Views&lt;/h3&gt;
A logical next step would be to extract the views out of the &lt;code&gt;SettingsPage&lt;/code&gt;  class, so that the latter only contains code related to the assembly of the settings page, while removing the code related to showing our project-specific fields and labels.
&lt;p&gt;GitHub Repository:
&lt;span&gt;&lt;/span&gt;  &lt;a href=&quot;https://github.com/schlessera/broken-settings-v2&quot;&gt;Example Code: Settings Page - Broken Implementation v2&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Our second iteration now has a very basic &lt;code&gt;View&lt;/code&gt;  class that can take a filename of a PHP view and render it when requested to do so. This way, we could add a mechanism to provide a path to custom views, and these custom views would be rendered instead of the default ones.&lt;/p&gt;
&lt;p&gt;The settings page still works as expected, but the actual text fields and labels that are being rendered come from separate view files, not from the &lt;code&gt;SettingsPage&lt;/code&gt;  class we want to make reusable. This is an improvement over our first iteration. However, it still falls short of our primary goal:&lt;/p&gt;
&lt;ol&gt;
 	&lt;li&gt;The &lt;code&gt;SettingsPage&lt;/code&gt;  class still decides on the number and types of fields to provide.&lt;/li&gt;
 	&lt;li&gt;The &lt;code&gt;SettingsPage&lt;/code&gt;  class still decides what data to store and where to store it.&lt;/li&gt;
 	&lt;li&gt;The &lt;code&gt;SettingsPage&lt;/code&gt;  class still decides what menu entry to create.&lt;/li&gt;
&lt;/ol&gt;
These three points represent business logic that we can&apos;t easily fit within view files, so we need to find yet another method of splitting up the code. Points 1. &amp;amp; 2. could be solved by extracting a &quot;Model&quot; out of the class, analogous to the &quot;View&quot; we&apos;ve already extracted. We seem to be on our way to completing the &lt;a href=&quot;https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller&quot;&gt;&quot;MVC&quot; (&quot;Model-View-Controller&quot;) architectural pattern&lt;/a&gt; for this single reusable object...
&lt;p&gt;When we consider going that route, though, we quickly realize that we&apos;ll end up writing more code creating custom models, views and controllers to make use of the &quot;reusable&quot; &lt;code&gt;SettingsPage&lt;/code&gt;  class than we originally needed for our first, non-reusable iteration. It seems as if, in this particular instance, the MVC pattern is not a good fit and will lead to a scenario where rewriting from scratch will be faster than reusing. Back to the drawing board then!&lt;/p&gt;
&lt;h3&gt;Back To The Drawing Board&lt;/h3&gt;
To create a reusable &lt;code&gt;SettingsPage&lt;/code&gt; , we don&apos;t want to create a complete architecture around it. At its most basic, we want to pass the business-specific code into the &lt;code&gt;SettingsPage&lt;/code&gt; , and it should then combine it with the reusable code to provide what we need...
&lt;p&gt;&lt;strong&gt;&lt;em&gt;How about injecting the business-specific code through the constructor?&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Conceptually, this would fit our needs. We could keep the two types of codes separate, and one type would then be injected into the other type at runtime. However, a practical implementation would quickly show that this is not a good method either. We&apos;d have a huge list of constructor arguments, which will make it very complicated to actually use our reusable class.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class SettingsPage {

    // Probably not worth exploring this concept further...
    public function __construct(
        $field_type_1,
        $filed_name_1,
        $field_label_1,
        $field_description_1,
        // ...
    ) {
        // Store the huge number of constructor arguments.
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;Well, how about injecting an associative array into the constructor then?&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This would indeed alleviate the problem of the growing argument list, and is something that is often used in procedural code bases like WordPress (see the hundred-and-one uses of the &lt;code&gt;$args&lt;/code&gt;  argument). The associative array can be injected through the constructor and stored as a property that will then be available for the rest of the code to consult.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class SettingsPage {

    /**
     * @var array
     */
    protected $args;

    /**
     * @param array $args Associative array of arguments.
     */
    public function __construct( array $args = [] ) {
        $this-&amp;gt;args = $args;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This associative array can contain labels, option names, section descriptions, etc... Also, as it can be multi-dimensional, we could provide an arbitrary number of fields or sections, and the reusable code could then adapt to the actual number the array provided.&lt;/p&gt;
&lt;p&gt;However, using such an array is not without issues:&lt;/p&gt;
&lt;ul&gt;
 	&lt;li&gt;If we type-hint against an array, we can&apos;t pass in an object implementing &lt;code&gt;ArrayAccess&lt;/code&gt; .&lt;/li&gt;
 	&lt;li&gt;If we don&apos;t type-hint against an array, we have no sanity check whatsoever.&lt;/li&gt;
 	&lt;li&gt;There&apos;s no convention on how to assemble the array.&lt;/li&gt;
 	&lt;li&gt;We cannot &quot;extend&quot; an array to provide validation and/or convenience functionality.&lt;/li&gt;
 	&lt;li&gt;We cannot easily inject an array through an auto-wiring injector.&lt;/li&gt;
 	&lt;li&gt;We cannot inject additional functionality into the array itself (like injecting a logger to log changes).&lt;/li&gt;
&lt;/ul&gt;
These issues are all more or less related to the fact that we are not injecting a real object here.
&lt;p&gt;&lt;em&gt;&lt;strong&gt;So, in essence, we&apos;d need something like an associative array, but as a real object, right?&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Yes!&lt;/strong&gt; Such an object would be injectable trough the reusable class&apos; constructor, and offer all the benefits of an associative array, while getting rid of the aforementioned issues that come with a pure array. Such an object is commonly called a &lt;strong&gt;Config&lt;/strong&gt; file/object/class. In case this should not be obvious, this is the short form for &lt;em&gt;Configuration&lt;/em&gt;, and it is called this way because it allows you to configure the parts of the reusable code that are not fixed. The fixed parts are hard-coded because there&apos;s no &quot;business-specific&quot; decision to be made about their implementation.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class SettingsPage {

    /**
     * @var ConfigInterface
     */
    protected $config;

    /**
     * @param ConfigInterface $config Configuration object.
     */
    public function __construct( ConfigInterface $config ) {
        $this-&amp;gt;config = $config;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When we inject such a Config object, the Config object itself can contain all sorts of logic, like for example providing means to validate its contents. Also, we can provide an extended, more specialized Config object whenever there&apos;s a need for additional functionality.&lt;/p&gt;
&lt;h3&gt;We Are On The Right Track&lt;/h3&gt;
The Config object seems to unite the advantages of an associative array with all the benefits of a real OOP approach. We&apos;ll examine such a Config object in detail in &lt;a href=&quot;/config-files-for-reusable-code-3/&quot;&gt;part 3 of this series&lt;/a&gt;. In the mean time, feel free to &lt;a href=&quot;#comments&quot;&gt;share your thoughts in the comments&lt;/a&gt;!
&lt;p&gt;&lt;em&gt;This is the second part of a series of articles. ( &lt;a href=&quot;/config-files-for-reusable-code/&quot;&gt;&lt;span&gt;&lt;/span&gt; Part 1&lt;/a&gt;, &lt;a href=&quot;/config-files-for-reusable-code-3/&quot;&gt;&lt;span&gt;&lt;/span&gt; Part 3 )&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content:encoded></item><item><title>Simple Examples For Complex Concepts?</title><link>https://www.alainschlesser.com/thinking/simple-examples-complex-concepts/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/simple-examples-complex-concepts/</guid><description>I&apos;m currently in the process of preparing a talk for  WordCamp Frankfurt  ( #WCFRA ) about a concept that enables you to make large parts of your code truly reusable....</description><pubDate>Wed, 31 Aug 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I&apos;m currently in the process of preparing a talk for &lt;a href=&quot;https://2016.frankfurt.wordcamp.org/&quot;&gt;WordCamp Frankfurt&lt;/a&gt; (&lt;a href=&quot;https://twitter.com/search?q=%23WCFRA&quot;&gt;#WCFRA&lt;/a&gt;) about a concept that enables you to make large parts of your code truly reusable. I&apos;m talking about the &quot;&lt;em&gt;store in a separate package and pull in via Composer&lt;/em&gt;&quot; type of reusability, not the &quot;&lt;em&gt;copy-paste and edit&lt;/em&gt;&quot; one.&lt;/p&gt;
&lt;p&gt;However, I&apos;m having real difficulty putting this concept into slides. Where I would have a large unit-tested class that can be reused as is and save hours of work in every future project, I end up with very complicated and over-engineered ways of &lt;a href=&quot;https://en.wikipedia.org/wiki/%22Hello,_World!%22_program&quot;&gt;greeting the world&lt;/a&gt;. It seems that some &lt;strong&gt;concepts that are useful and necessary in a given context (in regards to scope, &lt;/strong&gt;scale&lt;strong&gt; and complexity) are rendered meaningless when applied to a different context&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;I currently face this dilemma in several areas of my work. I am very passionate about software architecture and want to try to distil my findings into easily digestible pieces of content. &lt;strong&gt;But how do you sell benefits when your potential customers haven&apos;t faced the problems yet?&lt;/strong&gt; That is a very fundamental problem when trying to share &quot;best practices&quot;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;How do you sell benefits when your potential customers haven&apos;t faced the problems yet?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;ul&gt;
    &lt;li&gt;How do you show the benefits at scale when there is no scale?&lt;/li&gt;
    &lt;li&gt;How do you demonstrate the necessity to divide-and-conquer complexity without having complexity?&lt;/li&gt;
    &lt;li&gt;How do you explain the testing you can save when all you have is a `printf()`?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I&apos;ll probably manage to put together a decent slide deck for the coming presentation, but I am not entirely sure that I will be able to get my main points across. The slides will be available soon after the talk, so I&apos;ll let others be the judge...&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Have you faced a similar dilemma lately? &lt;a href=&quot;#comments&quot;&gt;Let me know in the comments!&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content:encoded></item><item><title>Using A Config To Write Reusable Code</title><link>https://www.alainschlesser.com/thinking/config-files-for-reusable-code/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/config-files-for-reusable-code/</guid><description>This is the first part of a series of articles. (     Part 2 ,     Part 3  )</description><pubDate>Mon, 08 Aug 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;em&gt;This is the first part of a series of articles. ( &lt;a href=&quot;/config-files-for-reusable-code-2/&quot;&gt;&lt;span&gt;&lt;/span&gt; Part 2&lt;/a&gt;, &lt;a href=&quot;/config-files-for-reusable-code-3/&quot;&gt;&lt;span&gt;&lt;/span&gt; Part 3&lt;/a&gt; )&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Object orientation lures you with the promise of making code reusable, letting you write source code once and then reusing it over and over in all of your projects. However, if you start delving into OOP territory, you&apos;ll probably notice rather soon that wrapping code in classes does not in and of itself make the code reusable. There are several things you need to take into consideration to produce truly project-independent objects.&lt;/p&gt;
&lt;p&gt;One of the issues you&apos;re facing is that you&apos;ll often end up with classes that contain a wild mixture of boilerplate code, that just takes care of the necessary plumbing, actual application logic that takes care of whatever you are trying to achieve, and also &quot;business logic&quot;, that guides the technical concerns into whatever direction that is needed to address the actual business needs.&lt;/p&gt;
&lt;p&gt;Your goal should not be to make the entirety of this mess reusable, but rather only the subset of boilerplate code and application logic. The business logic is per definition tied to a specific business need, so it cannot be reusable across different projects and clients.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Throughout this article series, we will use a basic settings page containing two text fields as an example to try different approaches. The settings page itself does not do anything meaningful, it only serves as an example.&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;A broken example&lt;/h3&gt;
Let&apos;s go through an example of a naïve OOP implementation of a settings page using the WordPress Settings API to see what the actual problem is.
&lt;p&gt;GitHub Repository:
&lt;span&gt;&lt;/span&gt;  &lt;a href=&quot;https://github.com/schlessera/broken-settings-v1&quot;&gt;Example Code: Settings Page - Broken Implementation v1&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;This is a first try at implementing our basic Settings page. It uses a &lt;code&gt;SettingsPage&lt;/code&gt; class that does all the work of setting up the page. This is proper OOP, right?&lt;/p&gt;
&lt;p&gt;No, not really. It is more or less procedural code wrapped in a &lt;code&gt;class&lt;/code&gt; syntax.&lt;/p&gt;
&lt;p&gt;Let&apos;s dig deeper into the code to see what the issue is.&lt;/p&gt;
&lt;p&gt;As you can see in the code linked above, we have a class that uses the WordPress Settings API to implement a settings page with 2 sections and a total of 4 settings. This class gets instantiated in &lt;a href=&quot;https://github.com/schlessera/broken-settings-v1/blob/master/src/Plugin.php#L39-L44&quot;&gt;lines 39-44&lt;/a&gt; of the &lt;code&gt;src/Plugin.php&lt;/code&gt; file and hooked up to the WordPress life-cycle.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public function init_settings_page() {
    // Initialize settings page.
    $settings_page = new SettingsPage();
    // Register dependencies.
    add_action( &apos;init&apos;, [ $settings_page, &apos;register&apos; ] );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As we have a class that manages our settings, can we already reuse this code in a different project?&lt;/p&gt;
&lt;p&gt;No, not really. It is true that we can reuse this class in a different project, but it will always take care of the exact same business needs. In this particular case, we can only reuse this class in a different project if we want to have a &quot;as-settings-broken-v1&quot; options page with the title &quot;Broken Settings v1 Settings Page&quot;, and which collects the first and last names to store them within the &lt;code&gt;assb1_settings&lt;/code&gt; option...&lt;/p&gt;
&lt;p&gt;As an example, let&apos;s examine the method &lt;code&gt;SettingsPage::options_page()&lt;/code&gt; (&lt;a href=&quot;https://github.com/schlessera/broken-settings-v1/blob/master/src/SettingsPage.php#L114-L128&quot;&gt;lines 114-128&lt;/a&gt; of the file &lt;code&gt;src/SettingsPage.php&lt;/code&gt;).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public function options_page() {
    ?&amp;gt;

&amp;lt;form action=&apos;options.php&apos; method=&apos;post&apos;&amp;gt;

&amp;lt;h2&amp;gt;Broken Settings v1 Settings Page&amp;lt;/h2&amp;gt;

        &amp;lt;?php settings_fields( &apos;pluginPage&apos; ); do_settings_sections( &apos;pluginPage&apos; ); submit_button(); ?&amp;gt;

    &amp;lt;/form&amp;gt;

    &amp;lt;?php
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Almost any options page built through the Settings API will have a form to be posted, that includes a heading, the registered settings sections and fields, as well as a submit button. However, the actual text of the heading will vary from project to project, as will the identifier of the fields and sections to render.&lt;/p&gt;
&lt;p&gt;Although our class is &quot;technically&quot; reusable, it is so limited in scope and flexibility that it will only ever be useful for reuse in the exact same project. This should make it obvious that OOP syntax in and of itself does not provide reusable code.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Object-oriented syntax in and of itself does not make your code reusable.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;Different Types Of Logic&lt;/h3&gt;
We can&apos;t easily reuse any of our source code from the example linked to above because we have wildly mixed both boilerplate code and business- or project-specific logic.
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/08/config-files-separation-01.svg&quot; alt=&quot;Conceptual drawing of code mixing both reusable code and project-specific code.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;If we take a more detailed look at the class we wrote for the SettingsPage (&lt;a href=&quot;https://github.com/schlessera/broken-settings-v1/blob/master/src/SettingsPage.php&quot;&gt;the file &lt;code&gt;src/SettingsPage.php&lt;/code&gt;&lt;/a&gt;), and try to find out for each specific statement and element, whether it is reusable, or project-specific, we can quickly see that there&apos;s no clear separation between these at all.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/08/config-files-code-breakdown.svg&quot; alt=&quot;Source code for SettingsPage class, with each word color-coded to distinguish between reusable and project-specific code.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Any piece of code that contains project-specific data or logic is per definition not reusable across projects. What&apos;s more, if we want to reuse code without copy-pasting, this means we need to be able to separate reusable and project-specific at the granularity level that is dictated by the way we pull in this code. This being a PHP example, we would most likely want to pull in this code via Composer, making our granularity level match a Composer package. If we intended to make a reusable &quot;Settings Page&quot; Composer package, the entire package must be completely devoid of project-specific data or logic.&lt;/p&gt;
&lt;p&gt;It becomes imperative then, that we have a very clear separation between reusable and non-reusable code, and we need to design our code so that these two types of logic are not intermingled.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/08/config-files-separation-02.svg&quot; alt=&quot;Conceptual drawing of code where reusable and project-specific parts are properly separated.&quot; /&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Design your code so that the reusable parts and the project-specific parts never intermingle.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Once we&apos;ve managed to fulfil this requirement, it is very easy to split out the reusable part of the code into a separate package, and, provided we&apos;ve done everything right, the project-specific part of the code will not even need to be changed to work with an external package instead of the included reusable part.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/08/config-files-separation-03.svg&quot; alt=&quot;Conceptual drawing of code where the reusable part has been split out into an external package.&quot; /&gt;&lt;/p&gt;
&lt;h3&gt;How To Achieve This Separation&lt;/h3&gt;
In the &lt;a href=&quot;/config-files-for-reusable-code-2/&quot;&gt;next part of this series&lt;/a&gt;, we will try to think of the possible ways of achieving this separation of reusable and project-specific code, and examine the concept of Config files more closely.
&lt;p&gt;&lt;strong&gt;As always, any feedback or questions are more than welcome! &lt;a href=&quot;#comments&quot;&gt;Just head over to the comments section and type away!&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;This is the first part of a series of articles. ( &lt;a href=&quot;/config-files-for-reusable-code-2/&quot;&gt;&lt;span&gt;&lt;/span&gt; Part 2&lt;/a&gt;, &lt;a href=&quot;/config-files-for-reusable-code-3/&quot;&gt;&lt;span&gt;&lt;/span&gt; Part 3&lt;/a&gt; )&lt;/em&gt;&lt;/p&gt;
</content:encoded></item><item><title>Bust That Cache Through A Content Hash</title><link>https://www.alainschlesser.com/thinking/bust-cache-content-hash/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/bust-cache-content-hash/</guid><description>During a recent discussion with fellow developers, we talked about how to get around caching issues with static assets and shared our approaches.</description><pubDate>Sun, 10 Jul 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;During a recent discussion with fellow developers, we talked about how to get around caching issues with static assets and shared our approaches.&lt;/p&gt;
&lt;p&gt;Every web developer knows the issue. You want to have your static assets be cached by the visitor&apos;s browser with a &lt;strong&gt;very long expiry date&lt;/strong&gt;. This accelerates the site on the visitor&apos;s site, reduces the strain and bandwidth usage on your server, and gives you good PageSpeed scores ( &lt;em&gt;= much SEO!&lt;/em&gt; ).&lt;/p&gt;
&lt;p&gt;However, when you start making changes to your site, you have to &lt;strong&gt;force a hard refresh&lt;/strong&gt; in your browser (or even worse, reset your static caching subsystem) to get your browser to actually download that changed version of the asset.&lt;/p&gt;
&lt;p&gt;That&apos;s why you want to include a &quot;&lt;strong&gt;cache busting&lt;/strong&gt;&quot; system, that suggests to the browser that, when you made a change in your static asset, that new file is actually different and should not be retrieved from the cache, but freshly downloaded.&lt;/p&gt;
&lt;p&gt;There are different approaches to achieve this, and I&apos;ll briefly touch upon the most common one before describing the method I use on my sites.&lt;/p&gt;
&lt;h3&gt;Using Query Strings&lt;/h3&gt;
&lt;p&gt;The most common approach within the WordPress sphere is to add a query string with the &lt;strong&gt;version&lt;/strong&gt; or with the &lt;strong&gt;file modification time&lt;/strong&gt; to the URL of the asset in question. Using the version in a query string is also what WordPress does out of the box to help you get around caches.&lt;/p&gt;
&lt;figure&gt;
&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/07/Screenshot-2016-07-10-11.13.55.png&quot; alt=&quot;Default WordPress behaviour is to append the version as a query string.&quot; width=&quot;964&quot; height=&quot;82&quot; /&gt;
&lt;figcaption&gt;Default WordPress behaviour is to append the version as a query string.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;The problem with this approach is that depending on what servers the visitor&apos;s connection is passing through, &lt;strong&gt;the assets will not be cached at all&lt;/strong&gt;. The query string appended to the end of the URL makes some proxy servers assume that the content of that file is dynamic in nature, and dependent on the current value of the query string.&lt;/p&gt;
&lt;p&gt;An example of why this is a reasonable assumption is the case of your search box. If the visitor enters something into that box and submits this search query, the URL will have a query string with the actual search terms appended to it: &lt;code&gt;&lt;a href=&quot;https://example.com/?s=my+search+terms&quot;&gt;https://example.com/?s=my+search+terms&lt;/a&gt;&lt;/code&gt; . You would not want to have one cached search result page be shared amongst all your visitor&apos;s, right?&lt;/p&gt;
&lt;p&gt;This is also the reason why some &lt;strong&gt;page speed analysis tools will flag your assets&lt;/strong&gt; if they contain such a query string.&lt;/p&gt;
&lt;p&gt;Both of the information bits suggested as values within the query string above also come with their specific disadvantages as well.&lt;/p&gt;
&lt;p&gt;Using the &lt;strong&gt;version string&lt;/strong&gt; means that you&apos;ll have to remember to &lt;strong&gt;manually bump&lt;/strong&gt; the version every time you make a change. This is boring and error-prone work, and will probably lead to instances where you forgot to bump the version.&lt;/p&gt;
&lt;p&gt;Using the &lt;strong&gt;file modification time&lt;/strong&gt; seems to avoid this, but comes with a different disadvantage. If you are using a task runner with an automated build pipeline, chances are that your asset will get completely rebuilt each time your task runner launches a new build. This means that all of your file modification times will &lt;strong&gt;change with every single change&lt;/strong&gt;, even if that change did not change any of the assets at all. This is wasteful, as the caches get invalidated much more often than is needed.&lt;/p&gt;
&lt;p&gt;Also, using the file modification time means that every page request will make a &lt;strong&gt;file access on every static asset&lt;/strong&gt; to collect these modification times. While these accesses are probably cached by the underlying filesystem, it might nevertheless have a negative performance impact.&lt;/p&gt;
&lt;h3&gt;A Better Approach&lt;/h3&gt;
&lt;p&gt;To improve upon the commonly used methods, the requirements are:&lt;/p&gt;
&lt;ol&gt;
    &lt;li&gt;&lt;strong&gt;No query strings, only a static URL.&lt;/strong&gt;&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Cache is only busted if this is actually needed.&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;To meet the first requirement, we put whatever information we need to bust the cache &lt;strong&gt;inside of the filename&lt;/strong&gt; itself. Easy, right?&lt;/p&gt;
&lt;p&gt;Well, turns out, this is not that easy at all. Having a &lt;strong&gt;changing component within the filename&lt;/strong&gt; makes it actually much more difficult to determine one of the data elements you need to generate the enqueueing URL: &lt;em&gt;...the exact filename&lt;/em&gt;!&lt;/p&gt;
&lt;p&gt;This is why we will need some kind of &lt;strong&gt;mapping information&lt;/strong&gt; that lets us deduce the current dynamically generated filename from a static filename or identifier.&lt;/p&gt;
&lt;p&gt;To meet the second requirement, we make the information we use to bust the cache &lt;strong&gt;depend on the actual contents of the file&lt;/strong&gt;. So, even if the file gets rebuilt through our task runner, it will not cause a cache bust until there was an actual change for that specific file.&lt;/p&gt;
&lt;p&gt;The usual way of achieving this is to generate a &lt;strong&gt;hash of the file contents&lt;/strong&gt;. For files with the same content, the generated hash will always be the same.&lt;/p&gt;
&lt;h3&gt;My Current Implementation&lt;/h3&gt;
&lt;p&gt;My static assets are run through a &lt;code&gt;gulp&lt;/code&gt; pipeline. &lt;code&gt;gulp&lt;/code&gt; is a task runner, and it allows me to &lt;strong&gt;automate my entire build process&lt;/strong&gt;. It can also watch my files, and relaunch the build process every time I save a change to one of the watched files.&lt;/p&gt;
&lt;p&gt;JavaScript files, for example, are all split up into individual modules. They are run through &lt;code&gt;browserify&lt;/code&gt;, where all the modules are concatenated, all dependencies pulled in, and everything is optimized and minimized. This results in one single JavaScript file that needs to be enqueued at the frontend.&lt;/p&gt;
&lt;p&gt;At the end of the gulp tasks for each of the static asset types, they are run through &lt;code&gt;gulp-rev&lt;/code&gt; (&lt;a href=&quot;https://github.com/sindresorhus/gulp-rev&quot;&gt;https://github.com/sindresorhus/gulp-rev&lt;/a&gt;). &lt;code&gt;gulp-rev&lt;/code&gt; reads the content and builds a &lt;strong&gt;10-char hash&lt;/strong&gt; out of it, and appends this to the filename: &lt;code&gt;unicorn.css&lt;/code&gt; → &lt;code&gt;unicorn-d41d8cd98f.css&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;It will also create a &lt;code&gt;rev-manifest.json&lt;/code&gt; file, that contains the &lt;strong&gt;mappings from the original name to the cache-busting name&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;I reconsolidate the &lt;code&gt;rev-manifest.json&lt;/code&gt; files from each of the asset type pipelines and save this file into the root of my &lt;code&gt;assets&lt;/code&gt; folder.&lt;/p&gt;
&lt;p&gt;Here&apos;s a real example of what such a &lt;code&gt;rev-manifest.json&lt;/code&gt; file will look like (in use on one of my sites):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;js/core.js&quot;: &quot;js/core-7ab954de.js&quot;,
  &quot;styles/atomic-editor.css&quot;: &quot;styles/atomic-editor-ff7ef446.min.css&quot;,
  &quot;styles/atomic.css&quot;: &quot;styles/atomic-8f3b28e1.min.css&quot;,
  &quot;js/frontend.js&quot;: &quot;js/frontend-ad0cbc15.js&quot;,
  &quot;js/backend.js&quot;: &quot;js/backend-9b0842cd.js&quot;,
  &quot;images/apple-touch-icon-114x114.png&quot;: &quot;images/apple-touch-icon-114x114-13efabdd.png&quot;,
  &quot;images/apple-touch-icon-120x120.png&quot;: &quot;images/apple-touch-icon-120x120-bc7f8566.png&quot;,
  &quot;images/apple-touch-icon-144x144.png&quot;: &quot;images/apple-touch-icon-144x144-97485e89.png&quot;,
  &quot;images/apple-touch-icon-152x152.png&quot;: &quot;images/apple-touch-icon-152x152-98ce2b7e.png&quot;,
  &quot;images/apple-touch-icon-180x180.png&quot;: &quot;images/apple-touch-icon-180x180-0bab6263.png&quot;,
  &quot;images/apple-touch-icon-57x57.png&quot;: &quot;images/apple-touch-icon-57x57-52911982.png&quot;,
  &quot;images/apple-touch-icon-60x60.png&quot;: &quot;images/apple-touch-icon-60x60-ed03722d.png&quot;,
  &quot;images/apple-touch-icon-72x72.png&quot;: &quot;images/apple-touch-icon-72x72-a6a33372.png&quot;,
  &quot;images/apple-touch-icon-76x76.png&quot;: &quot;images/apple-touch-icon-76x76-8d957963.png&quot;,
  &quot;images/apple-touch-icon-precomposed.png&quot;: &quot;images/apple-touch-icon-precomposed-8425b83a.png&quot;,
  &quot;images/apple-touch-icon.png&quot;: &quot;images/apple-touch-icon-a647c234.png&quot;,
  &quot;images/favicon-160x160.png&quot;: &quot;images/favicon-160x160-8a1a5695.png&quot;,
  &quot;images/favicon-16x16.png&quot;: &quot;images/favicon-16x16-b2e8ef41.png&quot;,
  &quot;images/favicon-192x192.png&quot;: &quot;images/favicon-192x192-d09408e5.png&quot;,
  &quot;images/favicon-32x32.png&quot;: &quot;images/favicon-32x32-44ee3da6.png&quot;,
  &quot;images/favicon-96x96.png&quot;: &quot;images/favicon-96x96-d35b3d6e.png&quot;,
  &quot;images/mstile-144x144.png&quot;: &quot;images/mstile-144x144-3da555ec.png&quot;,
  &quot;images/mstile-150x150.png&quot;: &quot;images/mstile-150x150-5a8bfc6f.png&quot;,
  &quot;images/mstile-310x150.png&quot;: &quot;images/mstile-310x150-93c9b526.png&quot;,
  &quot;images/mstile-310x310.png&quot;: &quot;images/mstile-310x310-42ed38f1.png&quot;,
  &quot;images/mstile-70x70.png&quot;: &quot;images/mstile-70x70-121de451.png&quot;,
  &quot;images/frontpage-hero.svg&quot;: &quot;images/frontpage-hero-b25d5717.svg&quot;,
  &quot;images/frontpage-service-01.svg&quot;: &quot;images/frontpage-service-01-02fc2962.svg&quot;,
  &quot;images/frontpage-service-02.svg&quot;: &quot;images/frontpage-service-02-3a9f4bd1.svg&quot;,
  &quot;images/frontpage-service-03.svg&quot;: &quot;images/frontpage-service-03-49e4e765.svg&quot;,
  &quot;images/logo.svg&quot;: &quot;images/logo-bb31c16a.svg&quot;,
  &quot;images/favicon.ico&quot;: &quot;images/favicon-31234638.ico&quot;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In my &lt;strong&gt;PHP backend code&lt;/strong&gt;, I have a function that lets me retrieve the cache-busting name from the standard name. It is basically just a &lt;strong&gt;lookup retrieved from the above mappings&lt;/strong&gt; file.&lt;/p&gt;
&lt;p&gt;Here&apos;s what such a function looks like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/**
 * Get cache-busting hashed filename from rev-manifest.json.
 *
 * @param  string $filename Original name of the file.
 * @return string Current cache-busting hashed name of the file.
 */
function get_asset_path( $filename ) {

	// Cache the decoded manifest so that we only read it in once.
	static $manifest = null;
	if ( null === $manifest ) {
		$manifest_path = get_stylesheet_directory() . &apos;/assets/rev-manifest.json&apos;;
		$manifest = file_exists( $manifest_path )
			? json_decode( file_get_contents( $manifest_path ), true )
			: [];
	}

	// If the manifest contains the requested file, return the hashed name.
	if ( array_key_exists( $filename, $manifest ) ) {
		return &apos;/assets/&apos; . $manifest[ $filename ];
	}

	// Assume the file has not been hashed when it was not foun within the
	// manifest.
	return $filename;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This allows me to &lt;strong&gt;just refer to the normal filename&lt;/strong&gt; without the hash within my source code. As an example, here&apos;s how to enqueue the frontend scripts:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;wp_enqueue_script(
	&apos;corescripts&apos;,
	get_stylesheet_directory_uri() . get_asset_path( &apos;js/core.js&apos; ),
	array( &apos;jquery&apos; ),
	null,
	true
);
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Using This Approach With Browser Injection&lt;/h3&gt;
&lt;p&gt;I want to note that it is not possible to combine a cache-busting approach that changes the filename with a live-reloading mechanism that uses &lt;strong&gt;browser injection&lt;/strong&gt; (like &lt;code&gt;browsersync&lt;/code&gt; ). Due to the nature of how browser injection works, it needs the file names to remain unchanged.&lt;/p&gt;
&lt;p&gt;So, you might want to plan on adding an option in your build pipeline to &lt;strong&gt;deactivate the cache busting during development time&lt;/strong&gt;, so that you can have fast live reloads when working on your stylesheets.&lt;/p&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;The above approach might be a bit more difficult to set up than going with the default WordPress behavior, but it provides obvious benefits. For sites where the right caching mechanisms become critical, a pipeline like the above should be considered a requirement.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;What about you, &lt;code&gt;dear( $reader );&lt;/code&gt;? Do you use an approach that differs from the ones I mentioned above? &lt;a href=&quot;#comments&quot;&gt;I&apos;d love to know about it!&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content:encoded></item><item><title>Including A Constructor In Your Interface</title><link>https://www.alainschlesser.com/thinking/including-constructor-interface/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/including-constructor-interface/</guid><description>Today, while looking through a pull request containing PHP code, I stumbled over an issue that is mostly non-existent in other languages, so it might be difficult to f...</description><pubDate>Wed, 06 Jul 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Today, while looking through a pull request containing PHP code, I stumbled over an issue that is mostly non-existent in other languages, so it might be difficult to find reliable information on best practices regarding this specific topic. I was, of course, delighted to see that the code in question included an interface and its related standard implementation, instead of a simple class. However, the interface included a constructor as well.&lt;/p&gt;
&lt;p&gt;When you try to find out whether you should include a constructor within interfaces, you&apos;ll probably end up realizing that this is not even possible in most other languages. PHP is very permissive in what it allows you to put into interfaces, sometimes to the point of making you consider choices you should not even be able to consider, to begin with.&lt;/p&gt;
&lt;p&gt;So, while you might already have guessed from that last statement that I&apos;m opposed to the idea of having constructors in an interface, even though PHP might allow it, I want to try to explain the reasoning behind my stance.&lt;/p&gt;
&lt;h3&gt;Contract About Interaction Between Objects&lt;/h3&gt;
&lt;p&gt;Object-oriented programming is about &lt;strong&gt;objects&lt;/strong&gt;, and how they &lt;strong&gt;communicate&lt;/strong&gt; with each other. An interface is a contract that fixes the details about how specific objects want to be interacted with. Through the interface, an object lets you know what vocabulary it understands. So, whoever the other party is, as long as it uses the correct vocabulary, it is welcome!&lt;/p&gt;
&lt;p&gt;I&apos;d like to quote a very important passage by &lt;strong&gt;Alan Kay&lt;/strong&gt; from a &lt;a href=&quot;http://lists.squeakfoundation.org/pipermail/squeak-dev/1998-October/017019.html&quot;&gt;mailing list discussion&lt;/a&gt; he had after being disappointed in what people generally perceived to be the most important point of object-oriented programming:&lt;/p&gt;
&lt;pre&gt;Just a gentle reminder that I took some pains at the last OOPSLA to try to remind everyone that Smalltalk is not only NOT its syntax or the class library, it is not even about classes. I&apos;m sorry that I long ago coined the term &quot;objects&quot; for this topic because it gets many people to focus on the lesser idea.

The big idea is &quot;messaging&quot; -- that is what the kernal of Smalltalk/Squeak is all about [...]. The Japanese have a small word -- ma -- for &quot;that which is in between&quot; -- perhaps the nearest English equivalent is &quot;interstitial&quot;. The key in making great and growable systems is much more to design how its modules communicate rather than what their internal properties and behaviors should be.&lt;/pre&gt;
&lt;p&gt;So, the interface does only and exclusively care about the &lt;strong&gt;interaction points between objects&lt;/strong&gt;. The instantiation (which is the constructor&apos;s responsibility) is not about how objects interact, but rather about how to turn a class (blueprint) into an object in the first place. At the point where the constructor comes into play, you don&apos;t even have an object yet.&lt;/p&gt;
&lt;h3&gt;Devoid Of Implementation Details&lt;/h3&gt;
&lt;p&gt;The constructor is used to &lt;strong&gt;put an object into an initialized state&lt;/strong&gt; when it is instantiated. The current state of an object, and whether it is considered valid or not, is an implementation detail, and should therefore not be relevant for the interface.&lt;/p&gt;
&lt;p&gt;The internal properties that define the state of an object should be inaccessible to outside objects. As the constructor should only deal with these internal properties, all of its work should therefore also be hidden from external objects as well.&lt;/p&gt;
&lt;p&gt;If you get passed a &lt;code&gt;View&lt;/code&gt;  object, and you want to render that view, you should not need to know whether that specific object had also asked for a &lt;code&gt;Logger&lt;/code&gt;  when being instantiated.&lt;/p&gt;
&lt;h3&gt;As Lean As Possible&lt;/h3&gt;
&lt;p&gt;The &lt;a href=&quot;https://en.wikipedia.org/wiki/Interface_segregation_principle&quot;&gt;Interface Segregation Principle&lt;/a&gt; (ISP), which is the &lt;em&gt;&lt;strong&gt;I&lt;/strong&gt;&lt;/em&gt; in &lt;em&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)&quot;&gt;SOLID&lt;/a&gt;&lt;/em&gt;, states that an interface should &lt;strong&gt;only contain the methods needed for one specific role&lt;/strong&gt;. So, as an (extremely simplified) example, when creating an interface for a &lt;code&gt;Validator&lt;/code&gt;  object, the interface probably should only contain the single method &lt;code&gt;validate()&lt;/code&gt; .&lt;/p&gt;
&lt;p&gt;If the interface contains too many methods, this probably points to a design issue where your interface just mirrors your classes. This might lead to code where different responsibilities are so tightly coupled that you can&apos;t make changes to one without affecting the other.&lt;/p&gt;
&lt;h3&gt;Consider Dependency Injection&lt;/h3&gt;
&lt;p&gt;When using &lt;a href=&quot;https://en.wikipedia.org/wiki/Dependency_injection&quot;&gt;dependency injection&lt;/a&gt; (and you really should), you usually pass in the dependencies of your object to be instantiated through its constructor. So, as an example, your console command might have an &lt;code&gt;Input&lt;/code&gt; dependency and an &lt;code&gt;Output&lt;/code&gt; dependency, so that it can receive input, parse it, and echo the corresponding output. This will yield a constructor along the lines of:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public function __construct(Input $input, Output $output);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, what if you now want to add logging to all of your console commands? You&apos;ll need an additional dependency on a &lt;code&gt;Logger&lt;/code&gt; as well. This will change your constructor, though. To keep the option of replacing one implementation with another one, you need to be able to adapt the constructor so that it can accept whatever dependencies you will need. And adapting the constructor should not break your existing code.&lt;/p&gt;
&lt;h3&gt;Consider Multiple Implements&lt;/h3&gt;
&lt;p&gt;If you do have your interfaces properly segregated, like described above, you might want to have a class that &lt;strong&gt;implements several interfaces at once&lt;/strong&gt;. As an example, you might want to have something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class CachedRenderer implements Cacheable, Renderable { }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In such a case, if both interfaces would include a constructor, they would dictate incompatible signatures for your class. You would not be able to write a constructor that would work with both, except in the rare case where their constructor is identical.&lt;/p&gt;
&lt;h3&gt;Instantiation Needs Implementations Details&lt;/h3&gt;
&lt;p&gt;The goal of using interfaces is to &lt;strong&gt;make your code agnostic of specific implementations&lt;/strong&gt;. Whenever you want to call a method declared in an interface, you can just rely on the object implementing the interface to accept that method call.&lt;/p&gt;
&lt;p&gt;Instantiation is different, though. You cannot instantiate a new object without knowing some implementation details about the specific class to use. At some point, whether it is directly in one of your classes or factories, or whether it is within an IoC container, you will need to write a statement along the lines of:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$object = new \ExactNamespace\ExactClassToInstantiate(
    $arguments,
    $thatThe,
    $exactClass,
    $needs
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is just not possible to instantiate a new object without knowing details about the implementation. That&apos;s why the instantiation is usually put within factories and/or DI containers, you want to have one single place to make changes if you want to replace classes.&lt;/p&gt;
&lt;h3&gt;What About The Liskov Substitution Principle?&lt;/h3&gt;
&lt;p&gt;The &lt;a href=&quot;https://en.wikipedia.org/wiki/Liskov_substitution_principle&quot;&gt;Liskov Substitution Principle&lt;/a&gt; (LSP), which is the L in &lt;a href=&quot;https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)&quot;&gt;SOLID&lt;/a&gt;, states that wherever an object is used, &lt;strong&gt;you should be able to replace it with a subtype of that object&lt;/strong&gt; without breaking the code. This means that your new object should be able to do everything that the original object could do or more.&lt;/p&gt;
&lt;p&gt;So, what about the example we&apos;ve given above where the subtype has a different constructor signature than the interface it implements. Won&apos;t this break the LSP?&lt;/p&gt;
&lt;p&gt;The LSP is not even concerned with instantiation at all. It does not state that you should be able to instantiate all classes in the same way. It only states that, when an object of a class is being used somewhere, it should be substitutable for an object of a subclass. Note the term &quot;object&quot; - we&apos;re already dealing with instantiated objects at this point. The LSP is still intact, even if we have different constructors for different implementations.&lt;/p&gt;
&lt;h3&gt;What If I Want To Enforce A Specific Signature?&lt;/h3&gt;
&lt;p&gt;If you absolutely must provide a specific signature to be used as part of your API, you are already defining one part of the specific implementation, not just the contract.&lt;/p&gt;
&lt;p&gt;In such a case, you should probably use an &lt;a href=&quot;http://php.net/manual/en/language.oop5.abstract.php&quot;&gt;abstract class&lt;/a&gt;. Within the abstract class, you can provide as much implementation details as wanted or needed, while also marking up the parts that the extending class will need to take care of. So, you have a kind of &lt;strong&gt;implementation spectrum&lt;/strong&gt; you can position your code on:&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;strong&gt;Interface&lt;/strong&gt; =&amp;gt; &lt;strong&gt;&lt;span&gt;no&lt;/span&gt;&lt;/strong&gt; implementation specifics provided&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Abstract Class =&amp;gt;&lt;/strong&gt; &lt;strong&gt;&lt;span&gt;some&lt;/span&gt;&lt;/strong&gt; implementation specifics provided&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Class&lt;/strong&gt; =&amp;gt; &lt;strong&gt;&lt;span&gt;all&lt;/span&gt;&lt;/strong&gt; implementation specifics provided&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;Don&apos;t put constructors into your interface definitions. They don&apos;t serve a valid purpose, and they might cause all sorts of issues down the road.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Did I miss something obvious? &lt;a href=&quot;#comments&quot;&gt;&lt;strong&gt;Let me know in the comments below!&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
</content:encoded></item><item><title>OOP-NOOB Series - That Which Cannot Be Named</title><link>https://www.alainschlesser.com/thinking/that-which-cannot-be-named/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/that-which-cannot-be-named/</guid><description>This article is part of the  OOP-NOOB Series .</description><pubDate>Mon, 20 Jun 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;em&gt;This article is part of the &lt;a href=&quot;/oop-noob-series-introduction/&quot;&gt;OOP-NOOB Series&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;What Are We Talking About Here?&lt;/h3&gt;
&lt;p&gt;Real namespaces were only introduced in PHP 5.3, so it is quite normal to see what is called &quot;&lt;strong&gt;poor man&apos;s namespacing&lt;/strong&gt;&quot; in codebases that were started before PHP 5.3, or that try to still support PHP versions older than that.&lt;/p&gt;
&lt;h3&gt;How Is It Being Used?&lt;/h3&gt;
&lt;p&gt;When no real namespace is being used, all the functions that are defined within a PHP script execution lifecycle share a common global namespace. Each name within that global namespace can only be defined once. When a name is already taken, PHP will throw a fatal error when defining it again. This is referred to as a &lt;em&gt;namespace collision&lt;/em&gt; (or &lt;em&gt;naming collision&lt;/em&gt;).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// ---[ File: as_silly_example_conflicting_syntax.php ]---

// Constant risking a naming collision.
const KEY = &apos;answer&apos;;

// Global variable risking a naming collision.
$data = [
    KEY =&amp;gt; 42,
];

// Function declaration risking a naming collision.
function get_data( $key ) {
    global $data;
    return $data[ $key ];
}

// ---[ File: use_as_silly_example_conflicting_syntax.php ]---

// Output will (probably not) be &quot;answer is 42&quot;.
echo KEY . &apos; is &apos; . get_data( KEY );
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When PHP did not yet have any namespaces, people (those who cared) generally used prefixes in front of everything that was to be defined within the global namespace (functions &amp;amp; global variables/constants). So, instead of risking that anyone else might also try to define the function &lt;code&gt;get_data()&lt;/code&gt;, they prefixed it with a vendor/author and/or project prefix, like &lt;code&gt;as_silly_example_get_data()&lt;/code&gt;. This greatly reduces the potential for collisions. However, it can quickly make the code unwieldy, as identifiers tend to get really long, while still not conveying any additional meaning.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// ---[ File: as_silly_example_prefix_syntax.php ]---

// Prefixed constant.
const AS_SILLY_EXAMPLE_KEY = &apos;answer&apos;;

// Prefixed global variable.
$as_silly_example_data = [
	AS_SILLY_EXAMPLE_KEY =&amp;gt; 42,
];

// Prefixed function declaration.
function as_silly_example_get_data( $key ) {
	global $as_silly_example_data;
	return $as_silly_example_data[ $key ];
}

// ---[ File: use_as_silly_example_prefix_syntax.php ]---

// Output will (more reliably) be &quot;answer is 42&quot;.
echo AS_SILLY_EXAMPLE_KEY
     . &apos; is &apos;
     . as_silly_example_get_data( AS_SILLY_EXAMPLE_KEY );
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is where the poor man&apos;s namespace comes into play! It wraps the entire code into one single class, which serves as a pseudo-namespace. Within that class, you can name your identifiers whatever you want, as long as the class name itself is safe from collisions.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// ---[ File: as_silly_example_class_syntax.php ]---

class AS_Silly_Example
{

    // Class-internal constant.
    const KEY = &apos;answer&apos;;

    // Class-internal variable.
    public $data = [
        self::KEY =&amp;gt; 42
    ];

    // Class-internal function (= method) declaration.
    public function get_data($key)
    {
        return $this-&amp;gt;data[$key];
    }

}

// ---[ File: use_as_silly_example_class_syntax.php ]---

// Output will (still) be &quot;answer is 42&quot;.
$example = new AS_Silly_Example();

echo AS_Silly_Example::KEY
    . &apos; is &apos;
    . $example-&amp;gt;get_data( AS_Silly_Example::KEY );
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So, with this version of the code, you can see that everything that is being referenced within the class is nice and short.&lt;/p&gt;
&lt;h3&gt;What&apos;s The Problem?&lt;/h3&gt;
&lt;p&gt;Now, when you extend the code above, every new function goes into your class (which makes it a method, btw). Your class will grow and grow, and you are relieved to know that you will never have to worry about a naming collision. &lt;em&gt;All swell, right?&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The main issue is that you might think that you&apos;re using object-oriented programming (OOP) principles. After all, you have a &lt;code&gt;class&lt;/code&gt; construct, and you&apos;re calling methods instead of functions... This is missing the point of what OOP is, though. &lt;strong&gt;OOP is not about syntax&lt;/strong&gt;. Calling something a &lt;code&gt;class&lt;/code&gt; does not make it OOP-y.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Wrapping a class around procedural code is not OOP. Still procedural, with different syntax.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;I will probably write a more elaborate article about what the main difference is between procedural programming and object-oriented programming at some point. There are lots of concepts that go hand in hand to make up the actual value that OOP provides. One of the more important ones is that it lets you split complexity in such a way that you can deal with only one part of the complexity without needing to bother about the rest. When you have a huge file with procedural code, wrapping that code in a &lt;code&gt;class { }&lt;/code&gt; does not help you in any way to better deal with the inherent complexity of that code.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;OOP lets you divide the overall complexity into smaller parts that you can deal with one at a time.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;You can, of course, split up procedural code as well. However, whenever you want to make a change to one part of it, you need to consider the effect on the entire rest of your code.&lt;/p&gt;
&lt;p&gt;What OOP brings to the table (and we&apos;re talking about a concept here, not a specific syntax) is &lt;strong&gt;contracts&lt;/strong&gt;. If you divide your code, a contract between these two separate parts sets up the requirements they need to fulfill. If that contract is properly set up, both parties can independently make changes without considering the other, for as long as they adhere to the terms of the contract.&lt;/p&gt;
&lt;p&gt;These contracts are one of the key concepts, and key benefits, that an OOP approach can provide.&lt;/p&gt;
&lt;h3&gt;Better Practice&lt;/h3&gt;
&lt;p&gt;What we have above in our last example is:&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;strong&gt;procedural code&lt;/strong&gt;&lt;/li&gt;
    &lt;li&gt;...where we need to deal with the &lt;strong&gt;entire complexity at once&lt;/strong&gt;&lt;/li&gt;
    &lt;li&gt;...where we add &lt;strong&gt;additional unnecessary complexity&lt;/strong&gt; by (ab)using class syntax&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If you really need to stay compatible with PHP 5.2 (and I don&apos;t recommend you do), then you can either go with the prefixed code or with the &lt;em&gt;poor man&apos;s namespacing&lt;/em&gt; technique, &lt;strong&gt;knowing that this is not OOP!&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If you use any PHP version greater or equal to 5.3, please, &lt;strong&gt;go with a real namespace&lt;/strong&gt; instead! If you&apos;re not comfortable writing proper OOP code, avoid the class syntax, it doesn&apos;t do much by itself.&lt;/p&gt;
&lt;p&gt;With our above example, this will produce the following code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/ ---[ File: as_silly_example_namespace.php ]---

namespace AS_Silly_Example;

// Namespaced constant.
const KEY = &apos;answer&apos;;

// Variables cannot be namespaced, so this is global and needs to
// be prefixed.
$as_silly_example_data = [
	KEY =&amp;gt; 42,
];

// Namespaced function declaration.
function get_data( $key ) {
	global $as_silly_example_data;
	return $as_silly_example_data[ $key ];
}

// ---[ File: use_as_silly_example_namespace.php ]---

// Import namespaced elements into current namespace.
// Note: Importing constants and functions only works for PHP 5.6+.
use AS_Silly_Example\KEY as the_key;
use AS_Silly_Example\get_data;

// Output will (still) be &quot;answer is 42&quot;.
echo the_key . &apos; is &apos; . get_data( the_key );
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There&apos;s a small issue with procedural code using namespaces in that you can&apos;t namespace a global variable. As you should strive to avoid global state anyway, this should not be a big deal.&lt;/p&gt;
&lt;p&gt;However, what we gained though is that there&apos;s a clear distinction in the consuming code between &lt;strong&gt;locating the different dependencies&lt;/strong&gt; (very explicit, each dependency needs to be carefully considered), and &lt;strong&gt;actually using them&lt;/strong&gt; once they&apos;ve been imported (very short and practical).&lt;/p&gt;
&lt;p&gt;So, using namespaces will lead to source code where each file begins by enumerating every single of its external dependencies (external to the own namespace). This is huge, as controlling the dependencies is one of the biggest headaches in software development.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Code with namespaces enumerates every single dependency, greatly helping to control them.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;While I doubt that this article will make you switch to using namespaces for all of your future code, I certainly hope that it helps to spread the notion that &lt;strong&gt;Object-Oriented Programming is not about syntax&lt;/strong&gt;.&lt;/p&gt;
</content:encoded></item><item><title>OOP-NOOB Series - Introduction</title><link>https://www.alainschlesser.com/thinking/oop-noob-series-introduction/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/oop-noob-series-introduction/</guid><description>There&apos;s lots of articles out there that try to explain valid Object-Oriented Programming concepts in PHP. While not all of them are good or even technically correct, t...</description><pubDate>Thu, 16 Jun 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;There&apos;s lots of articles out there that try to explain valid Object-Oriented Programming concepts in PHP. While not all of them are good or even technically correct, there&apos;s quite a volume of material that does an excellent job of showing how you can properly architect your code to adhere to commonly accepted best practices.&lt;/p&gt;
&lt;p&gt;However, no matter how many articles are published to show you how to do things correctly, I still see horrid code on a daily basis. People trying to use the OOP paradigm in PHP, but producing code that makes it obvious they have not even grasped the most basic of concepts yet, and therefore are not getting any of the benefits of OOP.&lt;/p&gt;
&lt;p&gt;So, as the number of &quot;&lt;em&gt;How to do X&lt;/em&gt;&quot; articles doesn&apos;t seem to have much positive effect on that evolution, I decided to start a &quot;&lt;em&gt;How &lt;strong&gt;NOT&lt;/strong&gt; to do X&lt;/em&gt;&quot; series of articles. I call this series the &quot;&lt;strong&gt;OOP-NOOB Series&lt;/strong&gt;&quot;, which stands for &quot;&lt;strong&gt;Object-Oriented Programming - No Object-Oriented Benefit&lt;/strong&gt;&quot;, and fittingly contains the disguised word &quot;&lt;strong&gt;Newb&lt;/strong&gt;&quot; for &quot;Newbie&quot; as well. It also references the term &quot;&lt;strong&gt;NOOP&lt;/strong&gt;&quot;, which stands for &quot;&lt;strong&gt;No Operation&lt;/strong&gt;&quot; in computer science,  a statement or command that just does not do anything at all.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;If, for whatever reason, you feel that any of the articles in this series concerns you personally, don&apos;t be offended by its silly title. I&apos;m just trying to be witty here. Everyone starts out as a beginner, just as I did at some point, and there&apos;s no shame in that. I&apos;m just less of a beginner than I was a few years ago, and I want to help other people make faster progress.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Each of the articles will cover one such anti-pattern that I commonly encounter, will discuss why people might use it, what problems it causes, and how to improve upon it. I&apos;m hopeful that this might be of value to people beginning to dabble in OOP, but who only have other people&apos;s shoddy code as an example to refer to.&lt;/p&gt;
&lt;p&gt;If you encounter any type of code or anti-pattern which you think I should cover, just let me know in the comments here, and I&apos;ll include it in the series if applicable.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;Note&lt;/strong&gt;: The code examples in this series will all be written in PHP, but the principles discussed should be language-agnostic and universally relevant.&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;Articles in this series:&lt;/h3&gt;
&lt;p&gt;&lt;em&gt;This list will grow over time.&lt;/em&gt;&lt;/p&gt;
&lt;ol&gt;
    &lt;li&gt;&lt;a href=&quot;/that-which-cannot-be-named/&quot;&gt;That Which Cannot Be Named&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;/oop-noob-series-the-publicity-stunt/&quot;&gt;The Publicity Stunt&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;The Rich Heritage &lt;em&gt;(coming soon)&lt;/em&gt;&lt;/li&gt;
    &lt;li&gt;Static Antics &lt;em&gt;(coming soon)&lt;/em&gt;&lt;/li&gt;
    &lt;li&gt;Religious Beliefs &lt;em&gt;(coming soon)&lt;/em&gt;&lt;/li&gt;
    &lt;li&gt;Self-ignition &lt;em&gt;(coming soon)&lt;/em&gt;&lt;/li&gt;
    &lt;li&gt;The Global Trotter &lt;em&gt;(coming soon)&lt;/em&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;...&lt;/p&gt;
</content:encoded></item><item><title>Adding A Central Autoloader To WordPress</title><link>https://www.alainschlesser.com/thinking/adding-central-autoloader-wordpress/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/adding-central-autoloader-wordpress/</guid><description>There&apos;s a new WordPress release cycle being started right now for WordPress 4.6, and the core developers have built a  wishlist  to collect the feature/change requests...</description><pubDate>Fri, 22 Apr 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;There&apos;s a new WordPress release cycle being started right now for WordPress 4.6, and the core developers have built a &lt;a href=&quot;https://make.wordpress.org/core/4-6/&quot;&gt;wishlist&lt;/a&gt; to collect the feature/change requests to consider for this release.&lt;/p&gt;
&lt;p&gt;One of the more interesting items on this list is the plan to include a central autoloader within WordPress Core (&lt;a href=&quot;https://core.trac.wordpress.org/ticket/36335&quot;&gt;#36335 - Next generation: core autoloader proposal&lt;/a&gt;), which could then be reused by plugins &amp;amp; themes.&lt;/p&gt;
&lt;p&gt;I recommended not building a custom autoloader for WordPress, but rather reuse the one provided with Composer. I&apos;d do this by first implementing a very quick version to just enable the autoloader at all, and then incrementally make changes to the existing Core code to make it autoloadable. Once the Composer&apos;s &lt;code&gt;composer.json&lt;/code&gt; schema is in place, it is very easy to add classes that are ready to be autoloaded.&lt;/p&gt;
&lt;p&gt;I have now made a quick test to see whether that approach is viable. And my conclusion, so far, is that &lt;strong&gt;this is probably much easier than people think&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;Basic Approach&lt;/h3&gt;
&lt;p&gt;Most of the discussions I read about adding an autoloader to WordPress make it seem like it would be necessary to do this as one big change that tries to autoload each and every file.&lt;/p&gt;
&lt;p&gt;However, this is not necessary at all. Having an autoloader available basically just means that, if you try to access a class, an interface or a trait that has not yet been declared for PHP, it will pass the name of the missing entity to the registered autoloader(s). If they return control to PHP, and the missing entity is still not declared, PHP will throw an error. So, at any moment in time, we need to make sure that each of the PHP constructs that are being used is either known to the registered autoloader &lt;strong&gt;OR&lt;/strong&gt; already loaded through a manual &lt;code&gt;include&lt;/code&gt;/&lt;code&gt;require&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;minimum viable autoloader&lt;/strong&gt; then is an empty autoloader without any class mappings, &lt;strong&gt;as long as all the rest of the required classes are loaded manually&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;This fact makes it possible to just load an empty autoloader to start, and then gradually make changes that combine the preparation of a class to be autoloaded with its inclusion into the autoloader&apos;s mappings, &lt;strong&gt;one class at a time&lt;/strong&gt;. This lets us just start with &lt;strong&gt;something&lt;/strong&gt;, and then continue to work on improving it until done.&lt;/p&gt;
&lt;h3&gt;Changing The &lt;code&gt;wp-load.php&lt;/code&gt; File&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;wp-load.php&lt;/code&gt; file is included in both the front-end and the back-end, and is responsible for providing the initial configuration of the site. This is a good place to hook our autoloader into.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;?php
/* [...] */

/** Define ABSPATH as this file&apos;s directory */
if ( ! defined( &apos;ABSPATH&apos; ) ) {
	define( &apos;ABSPATH&apos;, dirname( __FILE__ ) . &apos;/&apos; );
}

error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR );

// Load the PHP 5.2 compatible autoloader.
if ( ! file_exists( ABSPATH . &apos;/vendor/autoload_52.php&apos; ) ) {
	die( &apos;Autoloader was not found, aborting.&apos; );
}
require_once( ABSPATH . &apos;/vendor/autoload_52.php&apos; );

/* [...] */
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So, before loading &lt;code&gt;wp-config.php&lt;/code&gt;, we load our PHP 5.2 compatible autoloader.&lt;/p&gt;
&lt;h3&gt;Adding Our Classes To Composer&apos;s Autoloader&lt;/h3&gt;
&lt;p&gt;The above change makes our autoloader ready to be used, but it doesn&apos;t know anything about our classes yet.&lt;/p&gt;
&lt;p&gt;As a simple way to get started, we just let Composer parse the entire &lt;code&gt;wp-includes/&lt;/code&gt; folder. It will build a classmap that maps each class name to a file within that folder. We can later have this be more nuanced if needed, but for now, this is good enough.&lt;/p&gt;
&lt;p&gt;We also add the &lt;code&gt;xrstf/composer-php52&lt;/code&gt; package, which automates generating a PHP 5.2 compatible autoloader, as the default one only works with PHP 5.3.2+.&lt;/p&gt;
&lt;p&gt;Here&apos;s what a simple &lt;code&gt;composer.json&lt;/code&gt; would look like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;name&quot;: &quot;wordpress/wordpress&quot;,
  &quot;description&quot;: &quot;WordPress is web software you can use to create a beautiful website or blog.&quot;,
  &quot;keywords&quot;: [
    &quot;blog&quot;,
    &quot;cms&quot;
  ],
  &quot;type&quot;: &quot;wordpress-core&quot;,
  &quot;homepage&quot;: &quot;http://wordpress.org/&quot;,
  &quot;license&quot;: &quot;GPL-2.0+&quot;,
  &quot;authors&quot;: [
    {
      &quot;name&quot;: &quot;WordPress Community&quot;,
      &quot;homepage&quot;: &quot;http://wordpress.org/about/&quot;
    }
  ],
  &quot;support&quot;: {
    &quot;issues&quot;: &quot;http://core.trac.wordpress.org/&quot;,
    &quot;forum&quot;: &quot;http://wordpress.org/support/&quot;,
    &quot;wiki&quot;: &quot;http://codex.wordpress.org/&quot;,
    &quot;irc&quot;: &quot;irc://irc.freenode.net/wordpress&quot;,
    &quot;source&quot;: &quot;http://core.trac.wordpress.org/browser&quot;
  },
  &quot;require&quot;: {
    &quot;xrstf/composer-php52&quot;: &quot;1.*&quot;
  },
  &quot;scripts&quot;: {
    &quot;post-install-cmd&quot;: [
      &quot;xrstf\\Composer52\\Generator::onPostInstallCmd&quot;
    ],
    &quot;post-update-cmd&quot;: [
      &quot;xrstf\\Composer52\\Generator::onPostInstallCmd&quot;
    ],
    &quot;post-autoload-dump&quot;: [
      &quot;xrstf\\Composer52\\Generator::onPostInstallCmd&quot;
    ]
  },
  &quot;autoload&quot;: {
    &quot;classmap&quot;: [
      &quot;wp-includes/&quot;
    ]
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Well, Yes, But...&lt;/h3&gt;
&lt;p&gt;I know what you&apos;re thinking. That&apos;s exactly zero classes right now loaded through an entire autoloader system... big deal, right?&lt;/p&gt;
&lt;p&gt;Well, we do actually have an autoloader that is active for the entire WordPress Core. Let&apos;s try to examine what the implications are...&lt;/p&gt;
&lt;h4&gt;Doesn&apos;t Composer need PHP 5.3.2+?&lt;/h4&gt;
&lt;p&gt;Yes, it does, if you want to use it to pull in your dependencies. You do this at development time, though. So, just like most of the other development tools, this bumps requirements up. As an example, &lt;code&gt;grunt&lt;/code&gt;, the task runner that is used, needs &lt;code&gt;node.js&lt;/code&gt; and &lt;code&gt;npm&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;However, the development dependencies are different from the dependencies that the system needs at run-time on the production server. Once Composer has done its works during development, we have it generate a PHP 5.2 compatible autoloader, and this autoloader is the only thing we&apos;re using on the production server for now.&lt;/p&gt;
&lt;h4&gt;That&apos;s a huge overhead for not even loading classes through it, isn&apos;t it?&lt;/h4&gt;
&lt;p&gt;Yes, it is, and it would be a waste of resources if that was our end goal.&lt;/p&gt;
&lt;p&gt;But we only did this to enable an autoloader that can be used by WordPress Core and all plugins &amp;amp; themes. Once it is available, it is easily reused all over your site, making the small overhead negligible compared to the huge benefits. What&apos;s more, the better our code base gets, the more the autoloader will turn from an overhead into a performance optimization. Less unused code will be loaded, parsed and executed, less memory allocated.&lt;/p&gt;
&lt;h4&gt;How easy is it to move a class to the autoloader?&lt;/h4&gt;
&lt;p&gt;That mostly depends on how clean the code of that class already is. Let&apos;s use an easy example to see what the general work would involve.&lt;/p&gt;
&lt;p&gt;As an example, I want to have the &lt;code&gt;_WP_Editors&lt;/code&gt; class be autoloaded through Composer&apos;s autoloader. To do this, we need to first find out where it is &lt;code&gt;include&lt;/code&gt;d or &lt;code&gt;require&lt;/code&gt;d. To find these, we can just search through the code, looking for the file name &lt;code&gt;class-wp-editor&lt;/code&gt;: &lt;a href=&quot;https://github.com/WordPress/WordPress/search?utf8=%E2%9C%93&amp;amp;q=class-wp-editor&amp;amp;type=Code&quot;&gt;Search Results on GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Here&apos;s a list of code locations where that class is loaded:&lt;/p&gt;
&lt;ol&gt;
    &lt;li&gt;&lt;code&gt;/wp-includes/general-template.php&lt;/code&gt; (&lt;a href=&quot;https://github.com/WordPress/WordPress/blob/3e2e0c52e6c9363068abc169fe048346bd8baa12/wp-includes/general-template.php#L2846-L2847&quot;&gt;lines 2846-2847&lt;/a&gt;)&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;/wp-admin/includes/deprecated.php&lt;/code&gt; (&lt;a href=&quot;https://github.com/WordPress/WordPress/blob/21bdbc204eb79468738093524f4d7f717c9f3b7e/wp-admin/includes/deprecated.php#L752-L753&quot;&gt;lines 752-753&lt;/a&gt;)&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;/wp-admin/includes/ajax-actions.php&lt;/code&gt; (&lt;a href=&quot;https://github.com/WordPress/WordPress/blob/c3fe61770c5342877407bc143cc1a2590afcf93a/wp-admin/includes/ajax-actions.php#L1494&quot;&gt;line 1494&lt;/a&gt;)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;For each of these, we will remove the code that checks for the class&apos; existence, as well as the code that loads it if necessary (meaning we just delete the lines that were highlighted in the links).&lt;/p&gt;
&lt;p&gt;Without the autoloader we&apos;ve discussed above, this will of course break our site as soon as a page request tries to load the &lt;code&gt;_WP_Editors&lt;/code&gt; class.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/04/Screenshot-2016-04-22-07.55.13.png&quot; alt=&quot;Screenshot 2016-04-22 07.55.13&quot; /&gt;&lt;/p&gt;
&lt;p&gt;However, when you examine the classmap that Composer has generated, we can see that it also includes the &lt;code&gt;_WP_Editors&lt;/code&gt; class:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/04/Screenshot-2016-04-22-10.57.46.png&quot; alt=&quot;WordPress Composer Class Map&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Therefore, when we try the code with our autoloader active (loaded through the &lt;code&gt;wp-load.php&lt;/code&gt; file), we don&apos;t get an error message, the editor just pops up as expected.&lt;/p&gt;
&lt;p&gt;So, for all well-behaving classes, we can just remove the &lt;code&gt;include&lt;/code&gt;/&lt;code&gt;require&lt;/code&gt;  statements, and it will just work. Best of all: it will even work for plugins &amp;amp; themes.&lt;/p&gt;
&lt;h4&gt;Great! But what happens when we have a plugin that also includes a &lt;code&gt;composer.json&lt;/code&gt; file ?&lt;/h4&gt;
&lt;p&gt;It depends on how that plugin is installed. If it is installed through one of the normal paths like the &quot;Plugins&quot; screen, or uploading a ZIP file, this plugin&apos;s autoloader will just coexist with the central one we&apos;ve just created. It might cause conflicts if it depends on different versions of the libraries included with WordPress, but that would be bad behaviour in any case.&lt;/p&gt;
&lt;p&gt;If however that plugin was installed by adding it as a dependency into our central &lt;code&gt;composer.json&lt;/code&gt;, its autoloader would be combined and included within the central one. If there was a version conflict like discussed above, Composer would immediately let us know.&lt;/p&gt;
&lt;h4&gt;Ok, seems solid. But I&apos;m sure that not all the classes in WordPress can be loaded that way!&lt;/h4&gt;
&lt;p&gt;True. But this approach allows us to see how far we can get with easy changes, and then we&apos;ll be able to draw an inventory of what needs to change to complete the autoloader project. All the while, we can already use and test the autoloader, and reap some of the benefits.&lt;/p&gt;
&lt;h4&gt;Hmm... what about the procedural code? There&apos;s files full of functions in there...&lt;/h4&gt;
&lt;p&gt;Yes. Composer provides a mechanism that lets you define a list of &lt;code&gt;&quot;files&quot;&lt;/code&gt; that need to be included with the autoloader. This basically just &lt;code&gt;require&lt;/code&gt;s every single file that you provide within that list. So, even the files containing only functions or constants can be included.&lt;/p&gt;
&lt;p&gt;This is not useful in every case, but with a few small tweaks to the bootstrapping files, any issues can be easily overcome. And, for the overly difficult edge cases, we can still just leave the existing code in place until we find a better solution.&lt;/p&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Including an autoloader within WordPress is not an all-or-nothing endeavour.&lt;/strong&gt; With these simple changes, we have a fully functional autoloader being loaded with WordPress, and we can start refactoring the existing Core code to gradually load more and more classes (and even functions) through the autoloader.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;I would love to hear your feedback about this approach, so don&apos;t hesitate to &lt;code&gt;var_dump()&lt;/code&gt; your thoughts in my comments section below!&lt;/em&gt;&lt;/p&gt;
</content:encoded></item><item><title>Adding Git Hooks Through Composer Dev-Dependencies</title><link>https://www.alainschlesser.com/thinking/php-composter/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/php-composter/</guid><description>I have been working on refining my development workflow for some time now, in order to optimize the quality of my code. And as I am a big fan of automation, I tend to...</description><pubDate>Mon, 28 Mar 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I have been working on refining my development workflow for some time now, in order to optimize the quality of my code. And as I am a big fan of automation, I tend to look for tools that just do their work in the background and only need my input when my mental processing power is truly needed. This leads to a greater focus on the coding and problem solving area of development.&lt;/p&gt;
&lt;p&gt;One of the areas that was missing a satisfactory solution so far was the &lt;code&gt;pre-commit&lt;/code&gt; checks that &lt;code&gt;git&lt;/code&gt; was doing when new changes were committed to a repository. I had a bash script that was provided with my code, together with a small instruction in the &lt;code&gt;README.md&lt;/code&gt; file that was explaining how to symlink that file into the &lt;code&gt;.git/hooks&lt;/code&gt; folder. It did work, but it needed manual interaction first in order to be able to do its work.&lt;/p&gt;
&lt;h3&gt;Meet PHP Composter (&lt;em&gt;or&lt;/em&gt; It Which Has Been Misnamed)&lt;/h3&gt;
&lt;p&gt;To improve upon this, I have written a &lt;em&gt;Composer&lt;/em&gt; package that acts as a custom installer for &lt;em&gt;Git&lt;/em&gt; hooks. It has the very silly name of &lt;a href=&quot;https://github.com/php-composter/php-composter&quot;&gt;&lt;code&gt;PHP Composter&lt;/code&gt;&lt;/a&gt;, which is a word play on both &quot;&lt;em&gt;Composer&lt;/em&gt;&quot; and &quot;&lt;em&gt;Post-Commit&lt;/em&gt;&quot; (unfortunately, the package name &lt;code&gt;PrePosterous&lt;/code&gt; was already taken).&lt;/p&gt;
&lt;p&gt;You wouldn&apos;t use this package directly, though, as it will not do much. Instead, you will use packages of the type &lt;code&gt;php-composter-action&lt;/code&gt;, that depend upon the above package to be installed and configured as &lt;em&gt;Git&lt;/em&gt; hooks. Through a combination of custom &lt;em&gt;Composer&lt;/em&gt; installer code, the &lt;code&gt;&quot;extra&quot;&lt;/code&gt; key, and lots of intermediary files and symbolic links, this enables automatically attaching &lt;em&gt;PHP&lt;/em&gt; methods to &lt;em&gt;Git&lt;/em&gt; hooks.&lt;/p&gt;
&lt;h3&gt;The benefits of this approach&lt;/h3&gt;
&lt;ul&gt;
    &lt;li&gt;Code to be executed through &lt;em&gt;Git&lt;/em&gt; hooks is correctly defined and used as a development dependency. For production deployments (using &lt;code&gt;composer install --no-dev&lt;/code&gt;), the entire &lt;em&gt;PHP Composter&lt;/em&gt; stuff is simply ignored, without leaving any traces.&lt;/li&gt;
    &lt;li&gt;The dependency chain is used in the correct order. Your project does not depend on an executable like &lt;em&gt;PHP CodeSniffer&lt;/em&gt;, but rather on the one action that needs to be executed upon commit. This action then takes care of whatever stuff it needs.&lt;/li&gt;
    &lt;li&gt;The onboarding process for new developers is simplified, as they don&apos;t need to &quot;&lt;em&gt;create symlinks&lt;/em&gt;&quot;, &quot;&lt;em&gt;copy binaries&lt;/em&gt;&quot;, or whatever else is usually done. A single &lt;code&gt;composer install&lt;/code&gt; takes care of all that is needed to start developing.&lt;/li&gt;
    &lt;li&gt;The &lt;em&gt;Git&lt;/em&gt; hooks can be written in &lt;em&gt;PHP&lt;/em&gt; instead of &lt;em&gt;Bash&lt;/em&gt;, which is probably preferable for developers using &lt;em&gt;Composer&lt;/em&gt;.&lt;/li&gt;
    &lt;li&gt;The wiring up of the &lt;em&gt;Git&lt;/em&gt; hooks and the tools used by them is done through &lt;em&gt;Composer&lt;/em&gt;&apos;s A&lt;em&gt;utoloader&lt;/em&gt;, which avoids messing around with the local system&apos;s &lt;code&gt;PATH&lt;/code&gt; settings and environment variables.&lt;/li&gt;
    &lt;li&gt;As &lt;em&gt;Composer&lt;/em&gt;&apos;s &lt;em&gt;Autoloader&lt;/em&gt; is used, this also means that a large project with several dozen libraries will still only pull in each dependency like &lt;em&gt;PHP CodeSniffer&lt;/em&gt; once, instead of having small &lt;em&gt;Bash&lt;/em&gt; scripts duplicating across all projects.&lt;/li&gt;
    &lt;li&gt;The actual actions can be centrally maintained and updated, and a simple &lt;code&gt;composer update&lt;/code&gt; will incorporate any changes into existing packages.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If you&apos;re not interested in knowing more about the inner workings of this system, you don&apos;t need to read the rest of this blog post and should head straight to the &lt;a href=&quot;https://github.com/php-composter/php-composter#existing-php-composter-actions&quot;&gt;Existing PHP Composter Actions&lt;/a&gt; section of &lt;em&gt;PHP Composter&lt;/em&gt;&apos;s README file. There&apos;s only one existing action as of the time of this writing (&lt;a href=&quot;https://github.com/php-composter/php-composter-phpcs-psr2&quot;&gt;checking &lt;em&gt;PSR-2 Coding Style Guide&lt;/em&gt; compliance through &lt;em&gt;PHP CodeSniffer&lt;/em&gt;&lt;/a&gt;), and a second one is waiting for a &lt;a href=&quot;https://github.com/squizlabs/PHP_CodeSniffer/pull/936&quot;&gt;pull request&lt;/a&gt; to be merged into &lt;em&gt;PHP CodeSniffer&lt;/em&gt; to work correctly (checking &lt;em&gt;WordPress Coding Standards&lt;/em&gt; compliance through &lt;em&gt;PHP CodeSniffer&lt;/em&gt;).&lt;/p&gt;
&lt;h3&gt;Technical Details&lt;/h3&gt;
&lt;p&gt;To make this work, &lt;em&gt;PHP Composter&lt;/em&gt; will first tell &lt;em&gt;Composer&lt;/em&gt; to use an alternative installation path for packages of type &lt;code&gt;php-composter-action&lt;/code&gt;; instead of being installed into &lt;code&gt;vendor//&lt;/code&gt;, they will be installed into &lt;code&gt;.git/php-composter/actions/&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Then, &lt;em&gt;PHP Composter&lt;/em&gt; will look through the package&apos;s &lt;code&gt;&quot;extra&quot;&lt;/code&gt; key in &lt;code&gt;composer.json&lt;/code&gt; to find a key named &lt;code&gt;&quot;php-composter-hooks&quot;&lt;/code&gt; which contains mappings between &lt;em&gt;Git&lt;/em&gt; hook names and &lt;em&gt;PHP&lt;/em&gt; methods. It will then create a file &lt;code&gt;.git/php-composter/config.php&lt;/code&gt; that collects the mappings of all such packages.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;?php
// PHP Composter configuration file.
// Do not edit, this file is generated automatically.
// Timestamp: 2016/03/28 05:03:19

return array(
    &apos;applypatch-msg&apos; =&amp;gt; array(
    ),
    &apos;pre-applypatch&apos; =&amp;gt; array(
    ),
    &apos;post-applypatch&apos; =&amp;gt; array(
    ),
    &apos;pre-commit&apos; =&amp;gt; array(
        10 =&amp;gt; array(
            &apos;PHPComposter\PHPComposter_PHPCS_PSR2\Sniffer::preCommit&apos;,
        ),
    ),
    &apos;prepare-commit-msg&apos; =&amp;gt; array(
    ),
    &apos;commit-msg&apos; =&amp;gt; array(
    ),
    &apos;post-commit&apos; =&amp;gt; array(
    ),
    &apos;pre-rebase&apos; =&amp;gt; array(
    ),
    &apos;post-checkout&apos; =&amp;gt; array(
    ),
    &apos;post-merge&apos; =&amp;gt; array(
    ),
    &apos;post-update&apos; =&amp;gt; array(
    ),
    &apos;pre-auto-gc&apos; =&amp;gt; array(
    ),
    &apos;post-rewrite&apos; =&amp;gt; array(
    ),
    &apos;pre-push&apos; =&amp;gt; array(
    ),
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then, it will create symbolic links from each &lt;em&gt;Git&lt;/em&gt; hook ( &lt;code&gt;.git/hooks/&lt;/code&gt;) to the &lt;em&gt;Bash&lt;/em&gt; script &lt;code&gt;vendor/php-composter/php-composter/bin/php-composter&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#!/bin/bash

# ------------------------------------------------------------
# Git Hooks Management through Composer.
#
# @package   PHPComposter\PHPComposter
# @author    Alain Schlesser &amp;lt;alain.schlesser@gmail.com&amp;gt;
# @license   MIT
# @link      http://www.brightnucleus.com/
# @copyright 2016 Alain Schlesser, Bright Nucleus
# ------------------------------------------------------------

# Collect environment data.
hook=`basename &quot;$0&quot;`
package_root=`pwd`

# Make sure we have a PHP binary.
php=`which php`
if [[ $? -ne 0 ]]; then
    printf &quot;PHP binary could not be found. PHP Composter aborted.\n&quot;
    exit
fi

# Verify that the bootstrap.php file exists.
if [[ ! -f $package_root/.git/php-composter/includes/bootstrap.php ]]; then
    printf &quot;PHP Composter bootstrap file was not found. Please reinstall.\n&quot;
    exit
fi

# Launch the engine.
$php $package_root/.git/php-composter/includes/bootstrap.php $hook $package_root
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This shell script is only a small wrapper to launch the file &lt;code&gt;.git/php-composter/includes/bootstrap.php&lt;/code&gt; (a symbolic link to &lt;code&gt;vendor/php-composter/php-composter/includes/bootstrap.php&lt;/code&gt;), which is responsible for parsing the previously generated configuration file and calling the corresponding action.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;?php
/**
 * Git Hooks Management through Composer.
 *
 * @package   PHPComposter\PHPComposter
 * @author    Alain Schlesser &amp;lt;alain.schlesser@gmail.com&amp;gt;
 * @license   MIT
 * @link      http://www.brightnucleus.com/
 * @copyright 2016 Alain Schlesser, Bright Nucleus
 */

use PHPComposter\PHPComposter\Paths;

// Get the command-line arguments passed from the shell script.
global $argv;
$hook = $argv[1];
$root = $argv[2];

// Initialize Composer Autoloader.
if (file_exists($root . &apos;/vendor/autoload.php&apos;)) {
    require_once $root . &apos;/vendor/autoload.php&apos;;
}

// Read the configuration file.
$config = include Paths::getPath(&apos;git_config&apos;);

// Iterate over hook methods.
if (array_key_exists($hook, $config)) {

    $actions = $config[$hook];

    // Sort by priority.
    ksort($actions);

    // Launch each method.
    foreach ($actions as $calls) {
        foreach ($calls as $call) {

            // Make sure we could parse the call correctly.
            $array = explode(&apos;::&apos;, $call);
            if (count($array) !== 2) {
                throw new RuntimeException(
                    sprintf(
                        _(&apos;Configuration error in PHP Composter data, could not parse method &quot;%1$s&quot;&apos;),
                        $call
                    )
                );
            }
            list($class, $method) = $array;

            // Instantiate a new action object and call its method.
            $object = new $class($hook, $root);
            $object-&amp;gt;init();
            $object-&amp;gt;$method();
            $object-&amp;gt;shutdown();
            unset($object);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see from the code above, this will get the hook name from the small &lt;em&gt;Bash&lt;/em&gt; script that was executed, iterate over the configuration file to find the corresponding action, instantiate the action&apos;s class, and finally execute that action.&lt;/p&gt;
&lt;p&gt;This whole &quot;symlinking business&quot; is done on each &lt;code&gt;composer install&lt;/code&gt; and &lt;code&gt;composer update&lt;/code&gt; to always keep your &lt;em&gt;Git&lt;/em&gt; hooks current, and to avoid having stale links (for example, by removing the &lt;code&gt;vendor&lt;/code&gt; folder), &lt;em&gt;Composer&lt;/em&gt; is always told that the actions are not yet installed, to force a complete redeploy on each change.&lt;/p&gt;
&lt;p&gt;This is still a very early release for &lt;em&gt;PHP Composter&lt;/em&gt;, so I appreciate any feedback. I do think that this is very useful and I will incorporate it into all of my projects. I would be happy to hear about any other uses of &lt;em&gt;PHP Composter&lt;/em&gt; out in the wild, so do let me know of your specific use cases!&lt;/p&gt;
</content:encoded></item><item><title>Attracting Developers To WordPress</title><link>https://www.alainschlesser.com/thinking/attracting-developers-wordpress/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/attracting-developers-wordpress/</guid><description>Ryan McCue , Senior Engineer at  Human Made  and  WordPress Core Developer , has posted a series of tweets regarding the fact that WordPress is far from an ideal platf...</description><pubDate>Sat, 19 Mar 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;a href=&quot;https://twitter.com/rmccue&quot;&gt;Ryan McCue&lt;/a&gt;, Senior Engineer at &lt;a href=&quot;https://hmn.md/&quot;&gt;Human Made&lt;/a&gt; and &lt;a href=&quot;https://profiles.wordpress.org/rmccue&quot;&gt;WordPress Core Developer&lt;/a&gt;, has posted a series of tweets regarding the fact that WordPress is far from an ideal platform for developers, which has spawned a lot of discussion.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://twitter.com/rmccue/status/710464212183572481&quot;&gt;https://twitter.com/rmccue/status/710464212183572481&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://twitter.com/rmccue/status/710469646680399874&quot;&gt;https://twitter.com/rmccue/status/710469646680399874&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;As a long-form response to this, here&apos;s a list of changes I would like to see in WordPress, and how I would try to address backward compatibility (BC) concerns. I don&apos;t pretend to know that this is the absolute best way to tackle the problem, this is purely my own biased opinion, and how I would try to fix the issues if I were in charge.&lt;/p&gt;
&lt;p&gt;Keep in mind that I am mostly interested in having a &lt;strong&gt;robust&lt;/strong&gt;, &lt;strong&gt;future-proof&lt;/strong&gt; platform that is &lt;strong&gt;easy to maintain&lt;/strong&gt;. Some of the changes proposed below might be a disadvantage to the end-users without a developing background. One of the major hurdles that WordPress currently faces is that it tries to focus on &lt;strong&gt;end-users&lt;/strong&gt;, while actually increasing the need for &lt;strong&gt;developers&lt;/strong&gt; to implement solutions. That one paradox is probably at the heart of a lot of drama in recent times.&lt;/p&gt;
&lt;p&gt;I also want to mention that I don&apos;t list any of the more implementation-specific details, like whether there is a &lt;strong&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Separation_of_concerns&quot;&gt;Separation of Concerns&lt;/a&gt;&lt;/strong&gt;, whether the code is &lt;strong&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)&quot;&gt;SOLID&lt;/a&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Don%27t_repeat_yourself&quot;&gt;DRY&lt;/a&gt;&lt;/strong&gt;, etc... I only concentrate on the critical path from the now to a future where we can more easily get rid of cruft and improve at an accelerated pace. Once this we&apos;ve enabled this, taking care of the implementation specifics should be a piece of cake (hopefully)!&lt;/p&gt;
&lt;h3&gt;1. Bump PHP Version&lt;/h3&gt;
&lt;p&gt;I know this has been talked to death already, but it is still a major obstacle. WordPress needs to bump its &lt;strong&gt;minimum PHP version&lt;/strong&gt; requirement (not the recommended version). With great power comes great responsibility, and all the bragging about running one quarter of the web has a very bitter taste to it because of this.&lt;/p&gt;
&lt;p&gt;It is completely irresponsible and totally inexcusable to run a web server on PHP version 5.2 in 2016. By keeping the requirements this low, WordPress only caters to the people not ever looking after their servers, and the web hosting companies that sell very shoddy services to unknowing customers.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;This absolutely has to stop!&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Any serious hosting solution will keep their PHP version as current as possible, even if only to save money on reduced resource usage. I might even go so far as to connect the word &quot;malicious&quot; to 5.2 hosting...&lt;/p&gt;
&lt;p&gt;&lt;span&gt;&lt;strong&gt;Compatibility considerations:&lt;/strong&gt;&lt;/span&gt;
None, that&apos;s the whole point. Drop the compatibility with any version that has no security support, preferably even versions that have no active support.
&lt;em&gt;( &lt;a href=&quot;http://php.net/supported-versions.php&quot;&gt;Supported PHP Versions&lt;/a&gt; )&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;2. Use Namespaces&lt;/h3&gt;
&lt;p&gt;Developers have known for many decades now that polluting the global namespace is bad, and that it will come back to bite you. The fact that PHP was late to the party with introducing namespaces does not mean that we can continue to ignore this now.&lt;/p&gt;
&lt;p&gt;Imagine having all of your files (your photos, your videos, your documents, your operating system&apos;s files, your applications&apos; files, ...) be regrouped in one single folder. Bad idea, right? Everyone knows that....&lt;/p&gt;
&lt;p&gt;So, once we&apos;ve dealt with &lt;a href=&quot;#bump-php-version&quot;&gt;point 1.&lt;/a&gt; above, there&apos;s no valid reason not to use namespaces.&lt;/p&gt;
&lt;p&gt;&lt;span&gt;&lt;strong&gt;Compatibility considerations:&lt;/strong&gt;&lt;/span&gt;
To make the initial switch and provide legacy support for some time, the current functions can still stay and just redirect to the corresponding namespaced variants:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function wp_get_attachment_url( $id ) {
    \WP\Core\Attachment::get_url( $id );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3. Use an Autoloader&lt;/h3&gt;
&lt;p&gt;Once &lt;a href=&quot;#use-namespaces&quot;&gt;point 2.&lt;/a&gt; has been taken care of, it is very easy to integrate an autoloader into the mix. This goes hand in hand with &lt;a href=&quot;#use-composer&quot;&gt;point 4.&lt;/a&gt; below, as the package manager can tell the autoloader what namespaces need to be taken into account.&lt;/p&gt;
&lt;p&gt;&lt;span&gt;&lt;strong&gt;Compatibility considerations:&lt;/strong&gt;&lt;/span&gt;
None at all, autoloaders are already used all the time within WordPress plugins and themes. Combined with a proper architecture, an autoloader in WordPress Core will probably improve performance and memory consumption.&lt;/p&gt;
&lt;h3&gt;4. Use a Package Manager&lt;/h3&gt;
&lt;p&gt;Every non-trivial project reuses existing libraries and components. To avoid manual updating chores, this should be controlled and automated through a package manager, that pulls in dependencies and sub-dependencies. If this is combined with a corresponding way to define the needs of the project, the number of dependencies pulled in for WordPress Core could even be drastically reduced for most projects.&lt;/p&gt;
&lt;p&gt;In the PHP world, the de-facto standard for package management is &lt;strong&gt;&lt;a href=&quot;https://getcomposer.org/&quot;&gt;Composer&lt;/a&gt;&lt;/strong&gt;, and I don&apos;t see any valid reason not to use this as the package manager for WordPress projects. In fact, many developers already use Composer at the site level to update their entire project with one single command, with WordPress Core just being one of the many dependencies of a WordPress project.&lt;/p&gt;
&lt;p&gt;&lt;span&gt;&lt;strong&gt;Compatibility considerations:&lt;/strong&gt;&lt;/span&gt;
None at all, provided that &lt;a href=&quot;#bump-php-version&quot;&gt;point 1.&lt;/a&gt; above has been taken care of.&lt;/p&gt;
&lt;h3&gt;5. Use Semantic Versioning&lt;/h3&gt;
&lt;p&gt;When using an automated package manager like described in &lt;a href=&quot;#use-composer&quot;&gt;point 4.&lt;/a&gt;, it becomes hugely important to be able to control updates in an automated way, and to stop updates if they would break BC.&lt;/p&gt;
&lt;p&gt;That&apos;s what &lt;strong&gt;&lt;a href=&quot;http://semver.org/&quot;&gt;Semantic Versioning&lt;/a&gt;&lt;/strong&gt; is for. It would provide a way for automatic updates to just stop right before a BC would be introduced, and to also have security fixes that can be applied to previous, legacy versions.&lt;/p&gt;
&lt;p&gt;This would change the WordPress BC philosophy from &quot;&lt;em&gt;we don&apos;t break BC, ever&lt;/em&gt;&quot; to &quot;&lt;em&gt;we don&apos;t break BC for versions that are not meant to break BC&lt;/em&gt;&quot;, which, as you might have guessed, paves the way for &lt;strong&gt;controlled breaking of BC&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;span&gt;&lt;strong&gt;Compatibility considerations:&lt;/strong&gt;&lt;/span&gt;
None, this would be an easy improvement without any downside. Just start at some version and let people know what the versions mean.&lt;/p&gt;
&lt;h3&gt;6. Use Proper Object-Oriented Programming&lt;/h3&gt;
&lt;p&gt;I know that OOP is not the holy grail of development, but for a system of any non-trivial complexity, it is still heaps better than a procedural approach when it comes to maintainability and extensibility.&lt;/p&gt;
&lt;p&gt;The procedural code is in fact one of the reasons why it is so difficult to make changes to WordPress Core without breaking BC. You can&apos;t just extend an object and simply pass the extended version down the pipeline... there is nothing to extend, and there is no pipeline (whatever that may be), the plugins and themes are directly coupled to some of the innermost implementation details.&lt;/p&gt;
&lt;p&gt;I&apos;ve seen lots of efforts in this direction already, but I have to say that most of the &quot;classy&quot; code in WordPress Core is still very much procedural code written in class syntax, and the whole purpose is to switch from &quot;&lt;em&gt;emulating namespaces with prefixes&lt;/em&gt;&quot; to &quot;&lt;em&gt;emulating namespaces with classes&lt;/em&gt;&quot;, which should immediately stop in favour of point 2. above.&lt;/p&gt;
&lt;p&gt;OOP is not about syntax, it is about having &lt;strong&gt;decoupled&lt;/strong&gt; objects, that communicate with each other via &lt;strong&gt;contracts&lt;/strong&gt;. Everything should be coded against &lt;strong&gt;interfaces&lt;/strong&gt;, not concrete implementations. This way, the objects can be easily extended, and their implementations can be changed without breaking anything any dependent code.&lt;/p&gt;
&lt;p&gt;So, having a &lt;code&gt;WP_Post&lt;/code&gt; class is nice. Depending on a &lt;code&gt;WP_Post&lt;/code&gt; class is not. The plugins and themes should instead depend on a &lt;code&gt;WP\Core\Post&lt;/code&gt; interface, and know that, whatever object they will get, they will be able to call its &lt;code&gt;get_title()&lt;/code&gt; or &lt;code&gt;render_content()&lt;/code&gt; method. If WordPress Core decides to send them a &lt;code&gt;WP\GitHub\MarkDownGist&lt;/code&gt; which &lt;code&gt;implements WP\Core\Post&lt;/code&gt; instead, the theme should not need to care...&lt;/p&gt;
&lt;p&gt;&lt;span&gt;&lt;strong&gt;Compatibility considerations:&lt;/strong&gt;&lt;/span&gt;
As with &lt;a href=&quot;#bump-php-version&quot;&gt;point 1.&lt;/a&gt; above, the current functions, classes and methods could be kept, and would redirect to &lt;strong&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Facade_pattern&quot;&gt;Facades&lt;/a&gt;&lt;/strong&gt;, that serve the purpose of an &lt;strong&gt;&lt;a href=&quot;http://ddd.fed.wiki.org/view/anticorruption-layer&quot;&gt;Anti-Corruption Layer&lt;/a&gt;&lt;/strong&gt; between the current code and the new OOP code. The OOP code should be built to provide an optimal model, and ignore the requirements of the legacy code. The Facade will then translate between these two.
Using this approach, the new model can be built alongside the legacy one, and they can coexist as long as is necessary to get everyone migrated to the new model.&lt;/p&gt;
&lt;h3&gt;OOP Examples&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;#use-oop&quot;&gt;Point 6.&lt;/a&gt; is the biggie and should be the goal for the foreseeable future. Once there are proper abstractions for all the major subsystems and models that WordPress Core uses, and provided that they are properly decoupled from each other, it becomes trivial to replace specific parts with custom implementations.&lt;/p&gt;
&lt;p&gt;Let&apos;s take one of the suggestions people provided as an example and try to imagine how that could work in a proper OOP WordPress, so that it can be easily extended/customised.&lt;/p&gt;
&lt;h4&gt;Example - Routing&lt;/h4&gt;
&lt;p&gt;&lt;a href=&quot;https://twitter.com/rachelbaker/status/710798022737858560&quot;&gt;https://twitter.com/rachelbaker/status/710798022737858560&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://twitter.com/MZAWeb/status/710644905123651584&quot;&gt;https://twitter.com/MZAWeb/status/710644905123651584&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;People don&apos;t seem to like the way routing is handled in WordPress. Currently, the &lt;em&gt;WP Rewrite API&lt;/em&gt; is responsible for parsing your pretty permalinks, transforming them into a &lt;code&gt;WP_Query&lt;/code&gt; request, and dispensing developer headaches along the way. What would a flexible, extensible routing system look like for WP?&lt;/p&gt;
&lt;p&gt;Well, at a very basic level, we need a &lt;code&gt;WP\Core\RouterInterface&lt;/code&gt; that accepts a &lt;a href=&quot;https://github.com/php-fig/http-message/blob/master/src/ServerRequestInterface.php&quot;&gt;&lt;code&gt;Psr\Http\Message\ServerRequestInterface&lt;/code&gt;&lt;/a&gt; and chooses a matching object implementing the &lt;code&gt;WP\Core\RequestHandlerInterface&lt;/code&gt; that can &lt;code&gt;handle()&lt;/code&gt; that request.&lt;/p&gt;
&lt;p&gt;We&apos;d then have a &lt;code&gt;WP\Core\RewriteAPIRouter&lt;/code&gt; that &lt;code&gt;implements WP\Core\RouterInterface&lt;/code&gt; to provide the current behaviour.&lt;/p&gt;
&lt;p&gt;If you need something more than the standard &lt;em&gt;WP Rewrite API&lt;/em&gt;, you can either replace the &lt;code&gt;WP\Core\RewriteAPIRouter&lt;/code&gt; with a custom implementation that &lt;code&gt;implements WP\Core\RouterInterface&lt;/code&gt;, or you can wrap it with a &lt;a href=&quot;https://en.wikipedia.org/wiki/Decorator_pattern&quot;&gt;Decorator&lt;/a&gt;.&lt;/p&gt;
&lt;h4&gt;&lt;/h4&gt;</content:encoded></item><item><title>Type Declarations using Interfaces in PHP</title><link>https://www.alainschlesser.com/thinking/type-declarations-using-interfaces-php/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/type-declarations-using-interfaces-php/</guid><description>I&apos;ve recently completed a preliminary code audit on an existing WordPress plugin, and one of the goals I&apos;ve set for that audit was to decouple the code from the JavaSc...</description><pubDate>Mon, 14 Mar 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I&apos;ve recently completed a preliminary code audit on an existing WordPress plugin, and one of the goals I&apos;ve set for that audit was to decouple the code from the JavaScript library it was using, so that it could easily be extended to support future versions of that library.&lt;/p&gt;
&lt;p&gt;A question came back about the constructor syntax I was using, and how that actually worked. I&apos;ll use the opportunity to write the answer in form of a blog post, as I think that this is a concept that might be new to a lot of WordPress developers.&lt;/p&gt;
&lt;h3&gt;Let&apos;s Automate Watching of TV Series!&lt;/h3&gt;
&lt;p&gt;To explain the concept, let&apos;s assume we are writing a wrapper plugin for the awesome (and yet to be invented) &lt;code&gt;TV Series Watcher V1&lt;/code&gt; JavaScript library, which can automatically watch TV series for you, while you can concentrate on your actual work.&lt;/p&gt;
&lt;p&gt;In the plugin, I would have proposed a constructor like this for the wrapper plugin:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class WatcherPlugin {
   public function __construct( WatcherInterface $watcher ) {
      [...]
   }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The first thing that was new to the person asking the question is the way the argument inside of the constructor is written. Instead of just having an argument, &lt;code&gt;$watcher&lt;/code&gt;, we have two words that are related somehow (&lt;code&gt;WatcherInterface $watcher&lt;/code&gt;) for the first argument.&lt;/p&gt;
&lt;p&gt;As I have worked with several programming languages in the past, this is a very common thing for me. But as it turns out, this is &quot;rather new&quot; and less common in PHP usage.&lt;/p&gt;
&lt;p&gt;Having a qualifier in front of an argument name is called a &quot;&lt;em&gt;&lt;a href=&quot;http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration&quot;&gt;type declaration&lt;/a&gt;&lt;/em&gt;&quot;, and was only introduced with PHP 5.0 (when it was still called a &quot;type hint&quot;). With PHP 7.0 it was extended to be usable with scalar types too.&lt;/p&gt;
&lt;p&gt;It tells PHP what types of arguments to accept for the function call to be valid. If you now try to call this constructor by passing it the wrong type, you&apos;ll get a PHP error right away. You might for example try to pass in a string to the constructor:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$watcher_plugin = new WatcherPlugin( &apos;testing&apos; );
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will immediately trigger a fatal error (or throw a &lt;code&gt;TypeError&lt;/code&gt; exception in PHP7). So PHP itself simply does not allow you to call the constructor with a wrong argument. You can define what the requirements for your method are, and make sure that no one can call the method without fulfilling the requirements.&lt;/p&gt;
&lt;h3&gt;What are the Benefits of Using Type Declarations?&lt;/h3&gt;
&lt;p&gt;Here are some immediate benefits, in an arbitrary order:&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;You don&apos;t have to check the argument before starting to process it. So, you can avoid code like this:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;if ( ! $watcher instanceof WatcherInterface ) {
   return;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
    &lt;li&gt;As a side-effect of the previous benefit, you&apos;ll avoid hard-to-debug code where the method gets the wrong type of argument, but somehow it fits good enough for the code to not immediately break. This can happen if the argument is not immediately used, but rather passed on to other places in your code. It might even end up being stored in your database, and only causing an error a week later when it is eventually used.
You&apos;ll always want to have your errors be as close as possible (in source code as well as time) to your bugs!&lt;/li&gt;
    &lt;li&gt;It is one way of documenting what the exact requirements for your method are.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Why the Hate in PHP?&lt;/h3&gt;
&lt;p&gt;There are a few reasons why not everyone uses type declarations in PHP, and I want to quickly address these reasons.&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;strong&gt;It can have historical reasons.&lt;/strong&gt;
Before PHP5, there was no support for type declarations. PHP was built to be very &quot;convenient&quot; for coders, to &quot;quickly get the job done&quot;. With the growing success of PHP, projects became bigger and more complex. And as it turns out, &quot;convenient in the short term&quot; is often a synonym for &quot;comes back to bite you later on&quot;.
That&apos;s why PHP5 finally addressed this issue and added type declarations. It was not immediately possible to add them for scalar types, though, and we&apos;ve had to wait until PHP7 for these.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;It can indicate design flaws.&lt;/strong&gt;
Some developers mention that you can have differing type declarations when overriding methods, and that they prefer to have no type declarations rather than have them cause issues.
I personally have never perceived this as an obstacle, and I suspect that this points to a flaw in the architectural design of the application, rather than a technical limitation of the language. The whole point of using type declarations and interfaces is to have consistency amongst your methods and object interactions. When you go go on and mix these up, letting and extending class change the type declaration, goes against the very principle this is based upon.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;It is less useful in procedural programming.&lt;/strong&gt;
No scalar types before PHP7 together with no classes/interfaces means that type declarations are much less useful in procedural programming as they are in OOP.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Using Type Declarations with Interfaces&lt;/h3&gt;
&lt;p&gt;Okay, so now we know what a type declaration is. In our example above, we combine this with the use of an interface as well. We don&apos;t tell PHP: &quot;&lt;em&gt;I need an object of type &lt;code&gt;TVSeriesWatcherV1&lt;/code&gt; to work correctly.&lt;/em&gt;&quot;, but rather: &quot;&lt;em&gt;I need some kind of object that is able to fulfil the &lt;code&gt;WatcherInterface&lt;/code&gt; contract.&lt;/em&gt;&quot;. So what is this all about now?&lt;/p&gt;
&lt;p&gt;Interfaces let you define a contract between different components, so that they can interact with each other without caring about the actual implementation of their respective partners.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.alainschlesser.com/wp-content/uploads/2016/03/uml-diagram-watcherinterface.svg&quot; alt=&quot;UML Diagram showing the relationship between an interface, an abstract class and two concrete implementations.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;The above diagram shows how such a relationship would be visualised using UML (&lt;em&gt;&lt;a href=&quot;http://www.digilife.be/quickreferences/QRC/UML%20Reference%20Card.pdf&quot;&gt;quick PDF cheat-sheet&lt;/a&gt;&lt;/em&gt;).&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;WatcherPlugin&lt;/code&gt; only ever interacts with the &lt;code&gt;WatcherInterface&lt;/code&gt;, it does not know how the actual library should be implemented, or how many different versions there are. The &lt;code&gt;WatcherPlugin&lt;/code&gt;&apos;s code is very simple as a result:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class WatcherPlugin {

   protected $watcher;

   public function construct( WatcherInterface $watcher ) {
      $this-&amp;gt;watcher = $watcher;
   }

   public function play_episode( $episode ) {
      $this-&amp;gt;watcher-&amp;gt;watch( $episode );
   }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the pattern above is a basic version of &quot;&lt;a href=&quot;https://en.wikipedia.org/wiki/Dependency_injection&quot;&gt;Dependency Injection&lt;/a&gt;&quot;, meaning that the code itself does not go about retrieving its dependencies from all over the place, getting tightly coupled to the surrounding code in the process, but rather that it gets all of its dependencies injected through its constructor. The outside code needs to make sure that &lt;code&gt;WatcherPlugin&lt;/code&gt; gets everything it needs. &lt;code&gt;WatcherPlugin&lt;/code&gt; then stores the reference to this dependency inside of an internal property of its own, so that it can reuse that dependency later on.&lt;/p&gt;
&lt;h3&gt;Splitting up the Implementations&lt;/h3&gt;
&lt;p&gt;What we&apos;ve also done is that we&apos;ve split up the actual implementation into code that is reused by each version of the library, and code that changes between versions.&lt;/p&gt;
&lt;p&gt;The code that remains unchanged between versions goes into an abstract class &lt;code&gt;AbstractWatcher&lt;/code&gt; that &lt;code&gt;implements WatcherInterface&lt;/code&gt;. This lets us add all the boilerplate code that will never change between versions of the library.&lt;/p&gt;
&lt;p&gt;Then we have two different concrete implementations in our example, &lt;code&gt;TVSeriesWatcherV1&lt;/code&gt; and &lt;code&gt;TVSeriesWatcherV2&lt;/code&gt;, and each of them &lt;code&gt;extends AbstractWatcher&lt;/code&gt;.  Using this approach, once a new version &lt;code&gt;V3&lt;/code&gt; comes out, we can simply add a third &lt;code&gt;TVSeriesWatcherV3&lt;/code&gt; that also &lt;code&gt;extends AbstractWatcher&lt;/code&gt; and just add the small bit of code that needs to change between versions. The &lt;code&gt;WatcherPlugin&lt;/code&gt; does not need to be changed to be able to use this new version.&lt;/p&gt;
&lt;p&gt;So, when we combine this approach with the type declaration we&apos;ve used above, we&apos;ve written code that defines a very specific requirement using an interface: &quot;&lt;em&gt;&lt;code&gt;WatcherPlugin&lt;/code&gt; needs to receive an object that it can &lt;code&gt;watch()&lt;/code&gt;&lt;/em&gt;&quot;.&lt;/p&gt;
&lt;h3&gt;Another Round of Benefits&lt;/h3&gt;
&lt;p&gt;This opens the door to another set of benefits, that go far beyond what we&apos;ve identified before.&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;When correctly used with a robust &lt;em&gt;Dependency Injection Container&lt;/em&gt; (for example `&lt;a href=&quot;https://github.com/rdlowrey/auryn&quot;&gt;Auryn&lt;/a&gt;`), or &lt;em&gt;DIC&lt;/em&gt;, we can have the outside code tell the &lt;em&gt;DIC&lt;/em&gt; what exact version will be used in what context, and the &lt;em&gt;DIC&lt;/em&gt; will handle injecting the correct version into the `WatcherPlugin`&apos;s constructor automatically at runtime.&lt;/li&gt;
    &lt;li&gt;Completely external code can even extend the `AbstractWatcher` and register this external version with our &lt;em&gt;DIC&lt;/em&gt;. The plugin &quot;just works&quot; with that new external version, without ever having known about it.&lt;/li&gt;
    &lt;li&gt;We can run properly isolated unit tests with our `WatcherPlugin` by injecting a mock object that implements `WatcherInterface`. Unit tests should always be run in isolation, so that each method can be tested individually, without relying on any external context.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Phew!&lt;/h3&gt;
&lt;p&gt;This post touches a lot of advanced concepts, and some of these only make sense if you&apos;ve dabbled in object-oriented programming before. I hope that I&apos;ve been able to explain this in a way that it nevertheless makes some sense to most of you.&lt;/p&gt;
&lt;p&gt;I would love to hear from you fellow PHP developers!&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;Do you regularly use type declarations?&lt;/li&gt;
    &lt;li&gt;Do you make extensive use of interfaces to decouple your code?&lt;/li&gt;
    &lt;li&gt;What about dependency injection?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Hit the comments hard, this surely is a topic that needs more exposure in PHP&lt;/strong&gt;!&lt;/p&gt;
</content:encoded></item><item><title>PHP Feature Detection Library</title><link>https://www.alainschlesser.com/thinking/php-feature/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/php-feature/</guid><description>Link to GitHub Repository:  PHPFeature</description><pubDate>Thu, 14 Jan 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;em&gt;Link to GitHub Repository: &lt;a href=&quot;https://github.com/brightnucleus/phpfeature&quot;&gt;PHPFeature&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;I had a short conversation on Twitter the other day with Andrey Savchenko ( &lt;a href=&quot;https://twitter.com/Rarst&quot;&gt;@Rarst&lt;/a&gt; ). He was wondering whether feature-centric PHP requirements would work in WordPress extensions.&lt;/p&gt;
&lt;p&gt;Although he was talking about the features of the &quot;WP extensions&quot;, I asked myself why there was no feature detection library available for PHP, similar to what &lt;a href=&quot;https://modernizr.com/&quot;&gt;Modernizr&lt;/a&gt; does for the browser features. Traditionally, PHP requirements are always based on a version number constant.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://twitter.com/schlessera/status/687239552147288066&quot;&gt;https://twitter.com/schlessera/status/687239552147288066&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;Meet the PHPFeature Library&lt;/h3&gt;
&lt;p&gt;PHPFeature is a first draft of such a PHP Feature Detection Library. So, instead of checking for a specific PHP version number (which forces you to know and compare which features were introduced by which PHP versions), you can simply tell the library what features you need, and it will tell you with a simple boolean value whether these are supported or not. You can also ask the library about the absolute minimum version required to support the set of features you&apos;ve requested.&lt;/p&gt;
&lt;h3&gt;Why Bother?&lt;/h3&gt;
&lt;p&gt;What is the use of such a library? Well, for one, it simplifies knowing the required version you need for your code. Instead of building an entire matrix of version numbers, to find out what effective version is the most recent required one, you simply add the feature you intend to use to he array of features that gets passed in to the library.&lt;/p&gt;
&lt;p&gt;The features that are included in the reference list could also include more minor stuff. Although pretty much everyone knows when namespaces were added, knowing when a specific bug was fixed might be more obscure data that is harder to come by. So the features you are checking the support for might also include specific bug-fixes.&lt;/p&gt;
&lt;p&gt;The library could also be extended to include PHP extensions and libraries. So, instead of checking for a specific PHP version &lt;em&gt;or&lt;/em&gt; an extension &lt;em&gt;or&lt;/em&gt; a library, you could just check for the feature, and the library would tell you whether it is supported in &lt;em&gt;any&lt;/em&gt; of its possible forms.&lt;/p&gt;
&lt;h3&gt;How Do I Use It?&lt;/h3&gt;
&lt;p&gt;To include the library in your project, you can use Composer:&lt;/p&gt;
&lt;pre&gt;composer require brightnucleus/phpfeature&lt;/pre&gt;
&lt;p&gt;Alternatively, you can copy the classes inside of your application and make sure that your application can find them.&lt;/p&gt;
&lt;p&gt;Usage is pretty simple, it only comes with two methods so far.&lt;/p&gt;
&lt;pre&gt;public function is_supported( $features );&lt;/pre&gt;
&lt;p&gt;This returns a boolean value telling you whether all of the features that you passed in are supported by the current PHP version.&lt;/p&gt;
&lt;pre&gt;public function get_minimum_required( $features );&lt;/pre&gt;
&lt;p&gt;This returns a SemanticVersion object that contains the minimum PHP version that supports all of the features that you passed in.&lt;/p&gt;
&lt;p&gt;Here&apos;s an example as provided by the &lt;a href=&quot;https://github.com/brightnucleus/phpfeature/blob/master/README.md&quot;&gt;README.md&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;?php
/*
 * PHPFeature example usage code
 */

// Array of strings to define what features you need.
$features = array( &apos;namespaces&apos;, &apos;traits&apos; );

// Instantiate the PHPFeature library.
// When you don&apos;t provide a version number as the first argument,
// the version of the currently used PHP interpreter is fetched.
$php = new PHPFeature();

// Check whether all of the features are supported. If not...
if ( ! $php-&amp;gt;is_supported( $features ) ) {

    // ... throw exception and let user know the minimum needed.
    throw new RuntimeException( sprintf(
        &apos;Your PHP interpreter does not support some features needed to run this application. Please upgrade to version %1$s or newer.&apos;,
        $php-&amp;gt;get_minimum_required( $features )
    ) );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For more complex architectures, you could use this library to conditionally load certain files, or to conditionally extend classes with more advanced versions implementing the same interfaces.&lt;/p&gt;
&lt;h3&gt;Future Plans&lt;/h3&gt;
&lt;p&gt;This is more of a proof-of-concept, than a production-ready library at this stage. If there&apos;s interest in using a library like this, though, I can see it becoming a standardized way of dealing with different PHP versions in your code.&lt;/p&gt;
&lt;p&gt;One thing I would like to change is to lower the PHP requirement of the library itself to 5.2 (currently 5.3.2) so that it can be reliably used with WordPress.&lt;/p&gt;
&lt;p&gt;If you think that this approach might be useful in any way and want to contribute, just let me know or provide pull requests, all contributions are welcome.&lt;/p&gt;
&lt;p&gt;You can find the complete source code on GitHub:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/brightnucleus/phpfeature&quot;&gt;https://github.com/brightnucleus/phpfeature&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Is WordPress a Dependency?</title><link>https://www.alainschlesser.com/thinking/is-wordpress-a-dependency/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/is-wordpress-a-dependency/</guid><description>Should WordPress be treated just as any other dependency, or is WordPress equivalent to the website itself?</description><pubDate>Fri, 18 Sep 2015 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I am currently on a quest to find the perfect setup for my WordPress projects (who isn&apos;t, right?). I do think that a large part of what makes or breaks complex software projects is dependency management. And there are dependencies at every level of your projects, be they languages, libraries, servers, stakeholders, whatever. When someone pays you to attack a project (outside of hobbyism), he generally pays you to fulfil a business goal. And it&apos;s your task to keep the things in check upon which this business goal &quot;depends&quot; on.&lt;/p&gt;
&lt;p&gt;The problems you&apos;ll deal with when trying to manage these dependencies are not new to your project; they have been the same problems for many moons. And many smart people before you have found solutions to these, which can be found somewhere on a spectrum from &quot;satisfying&quot; to &quot;perfect&quot;.&lt;/p&gt;
&lt;p&gt;You&apos;ll probably agree that it is best to learn from other people&apos;s mistakes and reuse their solutions, instead of being stubborn and insisting on making these same mistakes yourself (wasting a lot of time &amp;amp; money in the process).&lt;/p&gt;
&lt;p&gt;On most levels that get touched by your project, the problem of &quot;dependency management&quot; has probably been solved already. For example, to be able to build a server stack that can run on any hardware, we have tools to virtualize/automate/abstract the entire hardware your stack could be dependent on.&lt;/p&gt;
&lt;p&gt;On the &quot;libraries&quot; or software level, you have different package managers that you can use, depending on what platform or programming language you like to work with. For the PHP language, the package manager of choice is &lt;a href=&quot;https://getcomposer.org/&quot;&gt;Composer&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;When I researched ways to include WordPress into a proper dependency management system for my software layer, I stumbled upon a &lt;a href=&quot;https://core.trac.wordpress.org/ticket/23912&quot;&gt;Core Trac ticket&lt;/a&gt; that had logged a debate I did not expect: whether WordPress was a dependency of a site, or whether it was the site itself. So, instead off discussing how to best pull WordPress in, the discussion veered off into a question of whether this was even a good idea in the first place.&lt;/p&gt;
&lt;p&gt;So here&apos;s how I see it (and I still have a lot to learn, I admit, so I&apos;m totally fine if you disagree). The point of starting a project to meet a business goal is usually to have some business logic be executed on business data. I don&apos;t want to go into any technicalities here on where the data comes from or how the logic is executed; these are details you should discuss with your local software engineer.&lt;/p&gt;
&lt;p&gt;But the business logic is the thing you are getting paid for. Everything else is just a dependency of making this work. So, I consider even the website itself to be a dependency, as you could also have a smartphone app, or staff members, or subcontractors, or a mainframe be responsible for executing this. As I am a software engineer and web developer, I tend not to be asked to manage anything but a software solution.&lt;/p&gt;
&lt;p&gt;Each dependency can have its share of sub-dependencies. So, if I say that my business goal is to collect a list of emails of potential customers, my main dependencies probably are a website and an email list provider. Now, the website dependency introduces a couple of new dependencies, like a domain name, a web server, etc. The web server again has sub-dependencies, like the OS it runs on, the scripting language and DB it uses, and so on.&lt;/p&gt;
&lt;p&gt;Somewhere rather deep inside these dependencies, you have WordPress, a CMS, that provides an abstraction of the DB and the web server (and some other things, too), so that you can better concentrate on implementing your business logic, instead of dealing with the DB directly or building endless user interface elements for management users.&lt;/p&gt;
&lt;p&gt;So, if we ignore all the levels above it, and just concentrate on the web site level ... is WordPress the site, or is it a dependency of the site? I would argue that it is pretty clear that WordPress is &quot;just&quot; a dependency, as you can have all sorts of stuff running alongside WordPress on your server. And the fact that there is a &lt;a href=&quot;http://v2.wp-api.org/&quot;&gt;WP-REST API&lt;/a&gt; project that will be integrated into WordPress core and that allows you to have a a public-facing front-end that can be another platform or language and that is completely separate from the WordPress backend tells me that at least a portion of the WordPress core developers agree.&lt;/p&gt;
&lt;p&gt;Although I understand the emotional attachment one might have to a project that is by your side for several years, I do think that the WordPress developers need to take a step outside of the WordPress ecosystem and exchange best practices with other platforms. Switching from [platform XYZ] to WordPress is a very frustrating experience so far, as the potential far exceeds the practical realities.&lt;/p&gt;
&lt;p&gt;I&apos;d love to have some feedback on this, as my conclusions might not be so &quot;evident&quot; as they seem to me.&lt;/p&gt;
</content:encoded></item><item><title>Woah, hold on a sec...</title><link>https://www.alainschlesser.com/thinking/woah-hold-on-a-sec/</link><guid isPermaLink="true">https://www.alainschlesser.com/thinking/woah-hold-on-a-sec/</guid><description>Hi there, how are you doing? I hope you&apos;re comfortable... I really need you to enjoy the reading experience here on this blog, as I need you to come back from time to...</description><pubDate>Thu, 17 Sep 2015 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Hi there, how are you doing? I hope you&apos;re comfortable... I really need you to enjoy the reading experience here on this blog, as I need you to come back from time to time.&lt;/p&gt;
&lt;p&gt;You see, I always try to stay &quot;professional&quot;, and &quot;unambiguous&quot;, and all sorts of other adjectives when communicating with clients and partners. But I want to build this site into a blog where I can also communicate in a more personal way, without censoring myself. To make this work, though, I&apos;ll probably need an audience to keep me motivated. That&apos;s where you, the reader, come into play.&lt;/p&gt;
&lt;p&gt;So, if you&apos;re okay with philosophical bouts and technical rants, paired with inadequate humour and word plays that seem witty to me only, you&apos;re very welcome! This blog will probably end up having posts about &quot;Software Development&quot;, &quot;Self-Employment&quot;, &quot;Technology&quot;, &quot;Uncategorized&quot;! I&apos;ll even throw in a &quot;Personal&quot; or two.&lt;/p&gt;
&lt;p&gt;You can probably see the area at the bottom of this post, right? This is where you can put in your complaints. Don&apos;t think my jokes are funny? Just let me know, and I&apos;ll make sure I&apos;ll perhaps consider eventual possibilities of optional change.&lt;/p&gt;
&lt;p&gt;This post has been dragging along already, and without much substance, so I&apos;ll stop here. But I count on you to be present when I publish the next post, so don&apos;t disappoint me, dear &quot;Reader&quot;! ;)&lt;/p&gt;
&lt;p&gt;See you on post #2!&lt;/p&gt;
&lt;p&gt;Alain&lt;/p&gt;
</content:encoded></item></channel></rss>