Cvuorinen.netDev notes & thoughts about web developmenthttp://cvuorinen.net/
Thu, 25 May 2017 17:52:55 +0000Thu, 25 May 2017 17:52:55 +0000Jekyll v3.4.3Running Angular tests in headless Chrome<p>Angular has some great tooling for running tests, namely Karma and Protractor. By default (at least when using Angular CLI) they run using Chrome. So when you execute the tests from command-line, it will pop open a browser window where the tests execute. This works well enough, but sometimes you either don’t want to see that browser window pop open or you are running the tests in an environment where there is no graphical environment (on a CI server or a Docker container for example).</p>
<p>There is nothing new in running Karma tests without a browser window, you have been able to do it with PhantomJS by installing the <code class="highlighter-rouge">karma-phantomjs-launcher</code>. PhantomJS has been good enough solution for this, but you might encounter some issues every now and then and need to add some additional polyfills etc. But Chrome now has the ability to run in <a href="https://www.chromestatus.com/feature/5678767817097216">headless mode since version 59</a>, so you can use it to run tests without needing to install any additional packages and with a more standard environment.</p>
<!--more-->
<h2 id="conf-your-karma">Conf your Karma</h2>
<p>Whether you have a Karma config generated with Angular CLI or one that you have created manually, you can use a config option called <strong>customLaunchers</strong> to create a new launcher based on an existing one by defining additional flags for it. This works equally with older AngularJS v1.x projects as well as newer Angular v2.x-4.x projects. To use Chrome in headless mode, you need to add the following section to your <code class="highlighter-rouge">karma.conf.js</code></p>
<div class="highlighter-rouge"><pre class="highlight"><code>customLaunchers: {
ChromeHeadless: {
base: 'Chrome',
flags: [
'--headless',
'--disable-gpu',
// Without a remote debugging port, Google Chrome exits immediately.
'--remote-debugging-port=9222',
],
}
}
</code></pre>
</div>
<p>Note, depending on your Chrome version, the <code class="highlighter-rouge">--disable-gpu</code> flag might not be needed.</p>
<p>Then you can replace whatever you had in the <code class="highlighter-rouge">browsers</code> section (either ‘Chrome’ or ‘PhantomJS’ etc.) with <code class="highlighter-rouge">ChromeHeadless</code>. That’s it, after that you can enjoy running your tests without any browser window popping up.</p>
<h2 id="e2e-tests-with-protractor">E2E tests with Protractor</h2>
<p>Running E2E tests in headless mode has been a bit more difficult, since it has not worked very nicely with PhantomJS. Basically your only option has been to run <a href="">Chrome in Xvfb</a> (that’s X virtual framebuffer in case you were wondering). But now it’s as simple as <a href="https://github.com/angular/protractor/blob/master/docs/browser-setup.md#using-headless-chrome">adding a few lines to your <code class="highlighter-rouge">protractor.conf.js</code></a> to also run your E2E tests in headless mode. You need to add the following options under the <code class="highlighter-rouge">capabilities</code> key (where you should already have <code class="highlighter-rouge">browserName: 'chrome'</code>):</p>
<div class="highlighter-rouge"><pre class="highlight"><code>chromeOptions: {
args: [ "--headless", "--disable-gpu", "--window-size=800x600" ]
}
</code></pre>
</div>
<p>See <a href="https://gist.github.com/cvuorinen/543c6f72f8ec917ebfd596802d387aa3">this Gist</a> for full examples of both <code class="highlighter-rouge">karma.conf.js</code> and <code class="highlighter-rouge">protractor.conf.js</code> (both files generated by Angular CLI with only the changes described above).</p>
<h2 id="go-forth-and-test-all-the-things">Go forth and test all the things</h2>
<p>Now you can just sit back and enjoy running all your tests without any distracting browser windows, or more importantly you can run them in your Continuous Integration server like Travis CI or Jenkins etc.</p>
<p>For more information, see <a href="https://developers.google.com/web/updates/2017/04/headless-chrome">Getting Started with Headless Chrome</a> on Google Developers.</p>
Fri, 05 May 2017 00:00:00 +0000http://cvuorinen.net/2017/05/running-angular-tests-in-headless-chrome/
http://cvuorinen.net/2017/05/running-angular-tests-in-headless-chrome/AngularTestingJavaScriptProgrammingUsing RxJS Observables with AngularJS 1<p>Reactive programming with RxJS has become quite popular lately in the frontend world, partly because it is included in Angular 2 and many people have already started learning it even though a stable version is not out yet. But if you are currently working with Angular 1, you don’t have to wait until you start using Angular 2 in your production apps to start using RxJS, since RxJS itself is stable and can be used with any framework.</p>
<p>Whether you already know RxJS and the reactive programming concepts, or just want to learn more about them before you start using Angular 2 for real, this post will show how you can integrate RxJS with Angular 1 and get into reactive programming right now.</p>
<!--more-->
<p>Reactive programming in itself is a complex topic, but there are many <a href="http://reactivex.io/tutorials.html">great tutorials</a> about it online so I will not cover it here in much detail. Some level of understanding about reactive programming concepts and Rx is assumed to be able follow along this post.</p>
<h2 id="rx-bindings-for-angularjs">Rx Bindings for AngularJS</h2>
<p>There is an official library for integrating RxJS with Angular 1 called <a href="https://github.com/Reactive-Extensions/rx.angular.js/">rx.angular.js</a>. This library works as a bridge between RxJS observables and AngularJS, making it easy to work with Observables in an Angular 1 application.</p>
<p>The main features of the library are:</p>
<ul>
<li>Trigger digest cycle on a scope when an observable emits a value</li>
<li>Create observables from scope watch expressions</li>
<li>Create observable functions on a scope</li>
<li>Convert scope events to observables</li>
</ul>
<p>Here is a small example where we create an autocomplete input field that can be used to search GitHub usernames:</p>
<script src="https://gist.github.com/cvuorinen/34494452537860b242d263cda82f482c.js"> </script>
<p>To create an observable that emits the input elements values, we create an observable function called <code class="highlighter-rouge">update</code> to the scope usig the <code class="highlighter-rouge">$createObservableFunction</code> scope method that <em>rx.angular.js</em> added. We then call that function in the template from the input element’s <code class="highlighter-rouge">ng-change</code>. You could also use <code class="highlighter-rouge">Rx.Observable.fromEvent(element, 'change')</code> if you have a reference to the input element, but in this case I wanted to showcase the features <em>rx.angular.js</em> offers and how they can be used with normal Angular directives etc.</p>
<p>After we have the input values as an observable, we need to create the autocomplete logic and make the network requests. So, here is a break down of what the code does:</p>
<ol>
<li>We wait until user has stopped typing with <code class="highlighter-rouge">debounce</code></li>
<li>Then trim any trailing whitespace</li>
<li>Filter out empty values</li>
<li>Only continue if value changed from previous (no new request if only added whitespace that was then trimmed)</li>
<li>Search GitHub using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch API</a> and convert the response to an Observable</li>
<li>Since we mapped the keyword to the search function that returned an Observable, we now have an Observable of Observables. So we use <code class="highlighter-rouge">switch</code> to flatten it back to a single Observable that will emit the search results. This will also discard the previous inner Observable if it was still running, making sure we get the results in correct order even if the network requests don’t complete in the same order that they were sent.</li>
<li>We then use <code class="highlighter-rouge">digest</code> method (added by <em>rx.angular.js</em>) to assign the emitted values to a property on the scope. This is needed since we need to trigger a digest cycle because we used Fetch instead of $http service.</li>
<li>Finally we have an empty subscription. It’s empty since we already assigned the emitted value to the scope, but it’s needed because Observables are lazy so nothing will happen if there are no subscriptions.</li>
</ol>
<p>Here is a link to a working JS Bin: <a href="http://jsbin.com/fekimuz/edit?js,output">jsbin.com/fekimuz</a></p>
<h2 id="async-pipe">Async pipe</h2>
<p>If you are familiar with Angular 2 development, you might know about the AsyncPipe (pipes are for Angular 2 what filters are for Angular 1). The Async pipe allows binding asynchronous values in the view, like so:</p>
<div class="language-liquid highlighter-rouge"><pre class="highlight"><code><span class="p">{{</span><span class="w"> </span><span class="nv">observable</span><span class="w"> </span><span class="p">|</span><span class="w"> </span><span class="nf">async</span><span class="w"> </span><span class="p">}}</span>
</code></pre>
</div>
<p>It works by creating a subscription to the observable that updates the view value when the Observable emits a new value. It also works with Promises (by adding a “then” callback that sets the view value to the resolved value).</p>
<p>There isn’t really anything magical about this implementation and I decided to make an Async filter so that I could use the same approach in Angular 1 applications, so I wrote <a href="https://github.com/cvuorinen/angular1-async-filter">angular1-async-filter</a>.</p>
<p>One of the key differences between Angular 1 and Angular 2 is the way the change detection works. In Angular 2 the pipes get a reference to the component change detector, that they can use to tell the change detection system that the component needs checking. In Angular 1 filters don’t have a way to get a handle of the current scope so that they would be able to trigger a digest cycle.</p>
<p>It was quite easy to make the <em>Async filter</em> work with $q promises, as they will automatically trigger a digest cycle, but RxJS Observables don’t have that kind of integration out of the box. You can of course use the <em>rx.angular.js</em> bindings mentioned above, and call <code class="highlighter-rouge">.digest()</code> on the Observable in your controller/service to make it work, but I started wondering if there was any way to pass the scope into the filter as a parameter. And turns out you can just use <code class="highlighter-rouge">this</code> as an argument in an expression to pass in the scope.</p>
<p>So I just added a check if a second argument was passed in and then use it to trigger a digest cycle in the listener when a new value is emitted. To use the <em>Async filter</em> without <em>rx.angular.js</em>, you need to pass in the scope like so:</p>
<div class="language-liquid highlighter-rouge"><pre class="highlight"><code><span class="p">{{</span><span class="w"> </span><span class="nv">observable</span><span class="w"> </span><span class="p">|</span><span class="w"> </span><span class="nf">async</span><span class="p">:</span>this<span class="w"> </span><span class="p">}}</span>
</code></pre>
</div>
<p>You can install the Async filter to your own Angular 1 project from npm like this:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>npm install angular1-async-filter --save
</code></pre>
</div>
<h3 id="async-filter-example">Async filter example</h3>
<p>As an example, here is the same autocomplete directive but this time using the <em>Async filter</em> instead of <em>rx.angular.js</em>:</p>
<script src="https://gist.github.com/cvuorinen/98447e065922e8e7e6860ffe1a94a3c6.js"> </script>
<p>Most of it is the same as before, here are the key differences:</p>
<ul>
<li>We create the Observable using the <code class="highlighter-rouge">fromEvent</code> method and pass in a reference to the input element. Since we are not using any Angular features here, there are no digests cycles happening on every key stroke.</li>
<li>Since the Observable will now emit the native DOM event, we need to dig out the actual input field string value (from the target.value property on the event).</li>
<li>After that it’s exactly the same as in the first example, except that there is no subscription and we store a reference to the final observable in a property on the scope (<code class="highlighter-rouge">scope.suggestions</code>).</li>
<li>Finally, in the view we use the Async filter on <code class="highlighter-rouge">suggestions</code>, which will subscribe to it and update the view when a new value is emitted. We also need to pass the current scope to it using <code class="highlighter-rouge">async:this</code> so that it can trigger a digest cycle, otherwise we would not see anything appear in the <code class="highlighter-rouge">ng-repeat</code>.</li>
</ul>
<p>Working JS Bin: <a href="http://jsbin.com/kelutu/edit?js,output">jsbin.com/kelutu</a></p>
<h2 id="conclusion">Conclusion</h2>
<p>As you can see, there is no reason you can’t use RxJS with your existing Angular 1 applications. You just need to understand how the Angular digest cycle works so that you know when you need to trigger it. <em>rx.angular.js</em> offers many ways you can integrate Observables to your Angular code base. My <em>Async filter</em> is a more simple approach, but it should cover the basic situation where you need to update the view at the end of an Observable pipeline. You could also go the most simple route and not add any additional dependencies at all, and just <code class="highlighter-rouge">.do(() =&gt; $scope.$applyAsync())</code> to trigger a digest cycle when an Observable emits a value. You can always start simple and add more libraries if you need more features.</p>
<p>Actually, the <em>Async filter</em> is not even limited to just working with RxJS observables, you could quite easily use it with other reactive libraries like <a href="https://baconjs.github.io/">Bacon.js</a> or <a href="https://rpominov.github.io/kefir/">Kefir.js</a>. You would just need to change the <code class="highlighter-rouge">.subscribe</code> method to use <code class="highlighter-rouge">.onValue</code> instead (pull requests are welcome to make it more interoperable).</p>
<p><br /><br />
Photo credits: <a href="https://www.flickr.com/photos/30602491@N00/15755743274/">Highway 101 by kromped</a> licensed under <a href="https://creativecommons.org/licenses/by-nc/2.0/">CC BY-NC 2.0</a> &amp; modified by me.</p>
Thu, 05 May 2016 00:00:00 +0000http://cvuorinen.net/2016/05/using-rxjs-observables-with-angularjs-1/
http://cvuorinen.net/2016/05/using-rxjs-observables-with-angularjs-1/AngularRxJSJavaScriptProgrammingBuilding a Deploy Button<p>I recently got a <a href="https://www.olimex.com/wiki/A20-OLinuXino-LIME">Olimex A20-OLinuXino-LIME</a> mini computer as a speaker gift for <a href="/2015/10/bulgaria-php-conference-2015-the-php-community/">speaking at the Bulgaria PHP Conference</a>. It’s quite similar to a Raspberry Pi, it has few USB ports, Ethernet port, HDMI output and some GPIO pins to hook up some electronics. Quite a lot of GPIO pins actually, a lot more than on Raspberry Pi. And it runs Debian Linux from an SD card. So it’s perfect for doing some hardware hacking and I have been building something on it last week.</p>
<p>I decided to build a deploy button for a project I’m working on at work. <!--more--> We are using <a href="/2013/06/installing-jenkins-ci-server-with-github-integration-for-a-php-project/">Jenkins CI server</a> and Capistrano for deploying. So the idea was to show build status from Jenkins with two LEDs, green when last build has succeeded and red when last build has failed. And blink the LED while a build is in progress, just as the icons in Jenkins web interface. And then pressing a button would execute a deploy using Capistrano (if the last build was successful).</p>
<p>There is a Python library for interfacing with the GPIO pins and I also found a nice Python library for interacting with Jenkins. There is also an <a href="https://github.com/JakDaniels/php-A10Lime">experimental PHP extension</a> for the OLinuXino GPIO interface, but I thought this would be a nice little project to brush up my Python skills, since I haven’t used it that much so I wanted to do it in Python.</p>
<p>If you are interested in building something similar on a Raspberry Pi, there is a <a href="https://github.com/ronanguilloux/php-gpio">PHP library</a> for the GPIO access and also a <a href="https://github.com/rwaldron/johnny-five">Javascript one</a>, so there is a lot to choose from.</p>
<h2 id="wiring">Wiring</h2>
<p>The GPIO pins on the OLinuXino are very small and close together, so a regular female jumper lead did not fit. I had to take away the plastic enclosure from the connectors and put some tape for insulation to be able to fit them on the pins. Not that difficult, but a little inconvenient.</p>
<p>Otherwise the wiring was easy as I already had <a href="http://ifgirlthencode.blogspot.com/2015/07/traffic-lights-part-1-wiring.html">some experience from building similar circuits</a> with the Raspberry Pi.</p>
<h2 id="case">Case</h2>
<p>I diced to build a case for the whole thing using Legos. We have used Legos with our <a href="http://ifgirlthencode.blogspot.com/2015/07/traffic-lights-part-2-coding-building.html">electronics projects I have done with my daughter</a>, so I had some ideas to add a lid over the button for example.</p>
<p>It came out quite nice and I was able to fit the button and the LEDs quite firmly using just Legos and nothing else. Could be better of course, but I’m happy with the end result and it’s good enough for the use case.</p>
<h2 id="programming">Programming</h2>
<p>The main program logic is quite simple, here is an excerpt that has the main loop:</p>
<div class="language-python highlighter-rouge"><pre class="highlight"><code><span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
<span class="k">if</span> <span class="n">buttonPressed</span><span class="p">()</span> <span class="ow">and</span> <span class="n">build</span><span class="o">.</span><span class="n">success</span><span class="p">():</span>
<span class="n">deploy</span><span class="p">()</span>
<span class="n">build</span><span class="o">.</span><span class="n">check</span><span class="p">()</span>
<span class="n">setLeds</span><span class="p">(</span><span class="n">build</span><span class="p">)</span>
<span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
</code></pre>
</div>
<p>You can see <a href="https://gist.github.com/cvuorinen/4a5b18fea1f4a65cea95">all of the code here</a>.</p>
<p>Here are some images of the end result:</p>
<p><a href="/assets/images/2015/10/2015-10-19-11.51.30.jpg"><img class="alignleft" src="/assets/images/2015/10/2015-10-19-11.51.30-300x222.jpg" width="300" /></a></p>
<div class="alignleft" style="width: 300px;">
<a href="/assets/images/2015/10/2015-10-19-11.52.09.jpg"><img src="/assets/images/2015/10/2015-10-19-11.52.09-300x222.jpg" width="300" /></a>
<p class="caption">HDMI and mini-USB ports can be accessed by opening the hatches.</p>
</div>
<p><a href="/assets/images/2015/10/2015-10-19-11.56.43.jpg"><img class="alignleft" src="/assets/images/2015/10/2015-10-19-11.56.43-300x222.jpg" width="300" /></a></p>
Mon, 19 Oct 2015 00:00:00 +0000http://cvuorinen.net/2015/10/building-a-deploy-button/
http://cvuorinen.net/2015/10/building-a-deploy-button/BGPHPContinuous IntegrationHardwarePythonHardware HackingBulgaria PHP Conference 2015 & the PHP Community<p>A week ago I attended the first <a href="http://www.bgphp.org/">Bulgaria PHP Conference</a> that was organized on September 26th and 27th 2015 in Sofia. Even though it was the first PHP conference in Bulgaria, the event was a real success. The venue was spectacular, the atmosphere was laid-back but still enthusiastic and energetic and the speaker line-up was very impressive.</p>
<!--more-->
<p>I presented a talk about AngularJS, yes a JavaScript talk even though it was a PHP conference. The organizers said that they wanted to have a diverse set of talks that includes something that you don’t come across at every PHP conference. AngularJS is the most popular JS framework at the moment, so many of us PHP developers get/have to work with it. There were also talks about topics such as testing, security, monitoring, graph databases, mentoring, data handling, API design and many others.</p>
<p>I could write a brief summary of all the talks I saw, or I could iterate over the things I learned, or tell you more about how well the conference was organized (but <a href="http://devwp.eu/bulgaria-php-conference-day-1-recap/">others</a> have already done <a href="http://andreas.heigl.org/2015/09/28/bulgaria-php-conference/">those</a>). I thought instead that I would write about a topic that has been on my mind since the event. And that’s the PHP community.</p>
<p>Both local and global communities have formed around many different technologies. Communities where developers share experiences, ask questions and help each other. Especially around open source technologies, there are many communities where the important things are not money, fame or who is the best, but instead sharing, openness and helping others without expectations or hidden agendas. And at least from my own experiences I can say that it is great to be a part of the global PHP community. Even though many of the speakers are well-known from different conferences around the world, or from popular open source projects, or work for some of the worlds largest tech companies, the atmosphere is warm and relaxed and nobody seems to think that they are “above others”.</p>
<p><a href="https://www.flickr.com/photos/bgphp/21820010222/"><img class="alignright" src="/assets/images/2015/10/21820010222_7bceb3326a_o-300x200.jpg" width="300" /></a>
Everyone is willing to help others, and you could clearly see that in the so-called “hallway track” of the conference, which many thinks is one of the best things about attending conferences. It means for example that anybody can come and ask for help about testing from the creator of the most popular PHP testing framework. And he will sit down, take out his laptop and show you and teach you. Even though people are willing to pay money for his books and workshops, it doesn’t stop him (and others) from helping fellow developers during the conference, just for the joy of helping others and being a part of the community.</p>
<p>One of the most important and rewarding things about attending conferences is networking with other people. Nowadays the talks are often recorded and published online, so you can watch them for free later. But the conversations with other like-minded people and forming real life-long friendships are the best things that a conference can offer. This also makes it possible that helping others is not only limited to the hallway track at the conference venue, but people can later chat and ask questions online through various platforms, such as Twitter, IRC, forums etc. It’s great to know that if needed, you can ask for testing related advice from a testing expert, or about new version of PHP from the people who took part in building it, or some tips for handling large quantities of data from a developer that works with the analytics data of some of the world’s largest websites.</p>
<p>Helping others within the PHP community is not limited to only technical things. Recently the PHP community has for example collected money for the family of a PHP developer that passed away unexpectedly to cover funeral expenses and donated money to a rent deposit for a core PHP developer when his family was struggling financially and had to live in a trailer for a while. No one had to donate money but the community members just wanted to help “one of their own”.</p>
<p>Since many of us are working using open source tools, that have in many cases been developed by volunteers without any monetary compensation for their work, it is important that we take part and give back. It can mean participating in the development of these tools by for example fixing bugs or writing documentation, or mentoring other developers, or whatever you can help with. It can be rewarding <a href="http://www.erikaheidi.com/blog/the-real-benefits-of-engaging-in-open-source">even in it’s own right</a>, but this way we can all take part in the global PHP community and be a part of something bigger than any one of us can be by ourselves or within the company we work for. And not limited only to the PHP community, but with all the open source communities we take part in.</p>
<p>PHP is definitely not the worlds best programming language from a technical view-point, but it is popular because it’s approachable to new developers, available in most hosting environments and well suited for web development. In addition to these, one of the biggest strengths of PHP in my opinion is the community around it. A community that I can proudly say I’m a part of.</p>
<p> </p>
<p>Photos borrowed from BGPHP (with permission), go check out more at <a href="https://www.flickr.com/photos/bgphp">flickr.com/photos/bgphp</a></p>
Mon, 05 Oct 2015 00:00:00 +0000http://cvuorinen.net/2015/10/bulgaria-php-conference-2015-the-php-community/
http://cvuorinen.net/2015/10/bulgaria-php-conference-2015-the-php-community/BGPHPCommunityConferencePHPConferencesWhat is Clean Code and why should you care?<p>Clean code is something that I have been interested in for a while now, and plan to write a series of blog posts about the different concepts related to clean code. In this introduction post to the series I will talk a little bit about what clean code actually is and also try to answer the question why should you care about clean code.</p>
<!--more-->
<h2 id="what-is-clean-code">What is Clean Code?</h2>
<p>Clean code is subjective and every developer has a personal take on it. There are some ideas that are considered best practice and what constitutes as clean code within the industry and community, but there is no definitive distinction. And I don’t think there ever will be.</p>
<p>After reading a few books on the topic, giving it some thought and delivering a couple of talks on the subject, if I had to summarize what clean code means in one sentence, I would say that for me:</p>
<blockquote>
<p>Clean code is code that is easy to understand and easy to change.</p>
</blockquote>
<p>Ok, that sounds nice, but what does it really mean? Let’s break that sentence apart and examine the individual points behind it.</p>
<p>Easy to understand means the code is easy to read, whether that reader is the original author of the code or somebody else. It’s meaning is clear so it minimizes the need for guesswork and possibility for misunderstandings. It is easy to understand on every level, specifically:</p>
<ul>
<li>It is easy to understand the execution flow of the entire application</li>
<li>It is easy to understand how the different objects collaborate with each other</li>
<li>It is easy to understand the role and responsibility of each class</li>
<li>It is easy to understand what each method does</li>
<li>It is easy to understand what is the purpose of each expression and variable</li>
</ul>
<p>Easy to change means the code is easy to extend and refactor, and it’s easy to fix bugs in the codebase. This can be achieved if the person making the changes understands the code and also feels confident that the changes introduced in the code do not break any existing functionality. For the code to be easy to change:</p>
<ul>
<li>Classes and methods are small and only have single responsibility</li>
<li>Classes have clear and concise public APIs</li>
<li>Classes and methods are predictable and work as expected</li>
<li>The code is easily testable and has unit tests (or it is easy to write the tests)</li>
<li>Tests are easy to understand and easy to change</li>
</ul>
<p>As I stated in the introduction, I plan to write a series of posts that cover these topics in more detail.</p>
<h2 id="why-should-you-care-about-clean-code">Why should you care about Clean Code?</h2>
<p>As Robert C. Martin stated in his book <a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882"><em>Clean Code: A Handbook of Agile Software Craftsmanship</em></a>, “Clean code is code that has been taken care of. Someone has taken the time to keep it simple and orderly. They have paid appropriate attention to details. They have cared.” But why should you care? What’s wrong with code that just works?</p>
<p>You should care because code is (almost) never written just once and then forgotten. Most of the time you, or someone else, need to work on the code. And to be able to work on it efficiently you need to understand the code.</p>
<p>And because people need to understand the code we write, we can say that the code we write is not intended only for the computer but also for humans.</p>
<blockquote>
<p>Programming is the art of telling another human what one wants the computer to do.<br />
— Donald Knuth</p>
</blockquote>
<p>If you write clean code, then you are helping your future self and your co-workers. You are reducing the cost of maintenance of the application you are writing. You are making it easier to estimate the time needed for new features. You are making it easier to fix bugs. You are making it more enjoyable to work on the code for many years to come. Essentially you are making the life easier for everyone involved in the project.</p>
<p>Now, I’m not saying you should get obsessed about clean code. Your code needs to provide value, so you can’t spend countless hours making it perfect. Clean code usually doesn’t happen on first try anyway, so you need to adopt a mindset that you will always strive to improve the code you are working on. You then need to decide when it is good enough and move on.</p>
<h2 id="conclusion">Conclusion</h2>
<p>In this post I have tried to explain what clean code means to me and also hopefully convinced you that you should also care about clean code (in case you didn’t previously).</p>
<p>My writing productivity has not been that good lately, but hopefully I will get around to writing more posts soon. So check back if you are interested. Also any feedback and comments would be greatly appreciated, either here or Twitter.</p>
<p>To close things up, I would like to share a few more of my favourite quotes and tweets I have come across lately.</p>
<blockquote>
<p>If you want your code to be easy to write, make it easy to read<br />
— Robert C. Martin</p>
</blockquote>
<blockquote>
<p>Clean code always looks like it was written by someone who cares. There is nothing obvious you can do to make it better.<br />
— Michael Feathers</p>
</blockquote>
<blockquote class="twitter-tweet" lang="en">Beautiful code, like beautiful prose, is the result of many small decisions. The right method length here, the right object name there.
— DHH (@dhh) <a href="https://twitter.com/dhh/statuses/447042824622850048">March 21, 2014</a></blockquote>
<blockquote class="twitter-tweet" lang="en">"Code is like humor. When you *have* to explain it, it’s bad" - <a href="https://twitter.com/housecor">@housecor</a>
— About Programming (@abt_programming) <a href="https://twitter.com/abt_programming/statuses/448101448564629504">March 24, 2014</a></blockquote>
<blockquote class="twitter-tweet" lang="en">“The cheapest time to refactor code is right now.” Great advices by <a href="https://twitter.com/bugroll">@bugroll</a> <a href="http://t.co/GGEQ8Bc3e1">http://t.co/GGEQ8Bc3e1</a> <a href="https://twitter.com/search?q=%23refactoring&amp;src=hash">#refactoring</a> <a href="https://twitter.com/search?q=%23cleancode&amp;src=hash">#cleancode</a>
— Luca Guidi (@jodosha) <a href="https://twitter.com/jodosha/statuses/446683743907237888">March 20, 2014</a></blockquote>
<blockquote class="twitter-tweet" lang="en">The cost of ownership for a program includes the time humans spend to understand it. Humans are costly, so optimize for understandability.
— Mathias Verraes (@mathiasverraes) <a href="https://twitter.com/mathiasverraes/statuses/457239755785506816">April 18, 2014</a></blockquote>
<blockquote class="twitter-tweet" lang="en">Dev time = 60% reading and 40% writing. Code refactor can reduce reading by 20%, improving 8 hours/week, or 416 hours/year. <a href="https://twitter.com/search?q=%23refactor&amp;src=hash">#refactor</a>
— Refactoring 101 (@refactoring101) <a href="https://twitter.com/refactoring101/statuses/453282385027534848">April 7, 2014</a></blockquote>
<script src="//platform.twitter.com/widgets.js" async="" charset="utf-8"></script>
Sat, 19 Apr 2014 00:00:00 +0000http://cvuorinen.net/2014/04/what-is-clean-code-and-why-should-you-care/
http://cvuorinen.net/2014/04/what-is-clean-code-and-why-should-you-care/Clean CodeProgrammingCQRS? Or did you mean (bumper) cars? – My PHPBenelux 2014 experience<p><img class="alignright" src="/assets/images/2014/01/phpbnl14.png" alt="" />
I recently attended the <a href="http://conference.phpbenelux.eu/2014/">PHPBenelux 2014</a> conference with a co-worker of mine. It was the 5th anniversary edition of PHPBenelux and the second time I attended the conference. It was held January 24th &amp; 25th at hotel Ter Elst in Antwerp, Belgium.</p>
<p>In this post I will recap my experience at the conference and highlight what I found most interesting, fun or otherwise noteworthy.</p>
<!--more-->
<h2 id="model-storming">Model Storming</h2>
<p>Friday started with half day workshops. We attended a work shop called <a href="http://conference.phpbenelux.eu/2014/sessions/#model-storming-workshop">Model Storming</a> by Mathias Verraes. It was a very interesting workshop that focused on building a domain model in small teams. We didn’t use any digital tools for this, but instead consumed massive amounts of Post-It notes of various colours. We received some good advice what kind of things you should think about and ask from customers (or “domain expert”) when designing software and some nice insight into Domain-driven design.</p>
<p>Mathias also presented a quick introduction to a concept called CQRS towards the end of the workshop. This is a very interesting concept. CQRS stands for <em>Command Query Responsibility Segregation</em>. Basically it means that there is a separate model for writing things and a separate model for reading things. CQRS combined with a concepts like <em>Event Sourcing</em> and <em>Task-based UI</em> provides some interesting capabilities where the UI sends commands to the write model, the write model turns them into events that get stored into an event store. The read model can then create all kinds of different representations of the data, even afterwards because the events can be replayed. CQRS seems interesting and I intend to learn more about it, in case you are interested you can check out some links <a href="http://cqrs.wordpress.com/">here</a>. The slides Mathias showed us can also be found <a href="http://verraes.net/2013/12/fighting-bottlenecks-with-cqrs/">here</a>.</p>
<h2 id="conference-time">Conference time</h2>
<p>After the workshop, the “main” conference began. It featured only one keynote (at the beginning) and after that 3 tracks of presentations for the friday afternoon and whole saturday. This year there was also an <a href="http://conference.phpbenelux.eu/2014/want-unconference/">UnConference</a>, which turned out to be quite popular and I think almost, if not all, of the available UnCon slots were taken.</p>
<p>The keynote was called <a href="http://conference.phpbenelux.eu/2014/sessions/#keynote-mentoring-developers">Mentoring Developers</a> by Elizabeth M Smith. Mentoring is a quite interesting topic and Elizabeth was clearly passionate about the topic. The talk was an interesting mix of the social and professional aspects of mentoring and stories from her personal experience. I enjoyed the talk a lot and it served as a good reminder that I really should get into this mentoring business myself.</p>
<h2 id="cqrs-or-did-you-mean-cars">CQRS? Or did you mean cars?</h2>
<p>Stijn Vannieuwenhuyse (who works with Mathias Verraes and was also helping out at the workshop) did an UnCon talk titled <a href="http://conference.phpbenelux.eu/2014/sessions/#sign-venue-present">CQRS? Or did you mean cars?</a>. The story behind the title is that some time ago when they first heard about CQRS it was so new that when they Googled for it, Google asked “Did you mean cars?”. This talk recapped most of the information about CQRS that Mathias presented in the morning, but offered some more in-depth code examples so it was very interesting.</p>
<h2 id="functional-design-patterns-under-the-hood">Functional Design Patterns Under the Hood</h2>
<p>We spent the rest of the afternoon learning <a href="http://conference.phpbenelux.eu/2014/sessions/#functional-application-design-php">Functional Application Design in PHP</a> by Michael John Burgess, <a href="http://conference.phpbenelux.eu/2014/sessions/#refactoring-design-patterns">Refactoring with Design Patterns</a> by Benjamin Eberlei and <a href="http://conference.phpbenelux.eu/2014/sessions/#php-performance-hood">PHP Performance: Under The Hood</a> by Davey Shafik. All of these talks were interesting and well presented and we learned a lot.</p>
<h2 id="bumper-cars">Bumper cars!</h2>
<p>After the last sessions of the day, it was time for the Conference Social. This year the organizers had really out done themselves and the social was a real success. There were the famous Belgian fries and always tasty Belgian beer and fun and games of various kind, including pinball, air-hockey, arcade games, mechanical bull rodeo and to top it all, bumper cars! The bumper cars were so much fun, but the most important thing in any social event are the people. It was great to meet so many friends and make new friends in such a relaxed and fun atmosphere. Really enjoyed it a lot.</p>
<p><a href="/assets/images/2014/01/2014-01-25-22.21.401.jpg"><img class="alignnone" src="/assets/images/2014/01/2014-01-25-22.21.401-300x166.jpg" alt="" width="300" /></a></p>
<h2 id="day-two-hemoglobin-and-hobgoblins">Day two: Hemoglobin and Hobgoblins</h2>
<p>In a multi track conference there will almost always be at least few slots where you really want to see more than one session. The organizers really wanted people to wake up early for day two, since all three of the first sessions were really interesting talks with great speakers. We decided to go see <a href="http://conference.phpbenelux.eu/2014/sessions/#models-service-layers-hemoglobin-hobgoblins">Models and Service Layers; Hemoglobin and Hobgoblins</a> by Ross Tuck. It was a great talk with some very good points, but you really had to pay attention to keep up. The <a href="http://www.slideshare.net/rosstuck/models-and-service-layers-hemoglobin-and-hobgoblins">first slide</a> really says it all. Ross also talked a little about CQRS towards the end of the presentation, are we starting to see a pattern here? There was also a link to a nice <a href="https://github.com/beberlei/litecqrs-php">PHP library for CQRS</a> by Benjamin Eberlei.</p>
<p>After recovering from the first talk of the day, we went to see <a href="http://conference.phpbenelux.eu/2014/sessions/#seven-deadly-sins-dependency-injection">The seven deadly sins of Dependency Injection</a> by Stephan Hochdörfer and after that <a href="http://conference.phpbenelux.eu/2014/sessions/#application-monitoring-heka-statsd">Application monitoring with Heka and statsd</a> by Jordi Boggiano.</p>
<h2 id="clean-code-at-the-uncon">Clean Code at the UnCon</h2>
<p>After lunch it was time for my UnConference talk <a href="http://joind.in/10482">Clean Code</a>. The room was full (I like to think it was all me, but the fact that Matthew Weier O’Phinney was right after me might also have something to do with it) and I think it went quite well. I really wish I would have had a little more time to prepare the talk and the slides, but I got some good feedback so I will keep working on it and maybe submit as a real talk to another conference someday. After my session Matthew demoed <a href="http://www.apigility.org/">Apigility</a> which seems great for building good APIs.</p>
<h2 id="extracting-and-closing">Extracting and Closing</h2>
<p>Last sessions we went to see were <a href="http://conference.phpbenelux.eu/2014/sessions/#social-human-architecture-beginners">Social human architecture for beginners</a> by Sebastian Schürmann which concentrated more on the human factor and <a href="http://conference.phpbenelux.eu/2014/sessions/#extract-till-drop">Extract Till You Drop</a> by Mathias Verraes which was a really nice live coding demo of refactoring legacy code.</p>
<p>After the last sessions it was time for the closing remarks, raffles and post-conference social. The organizing team gave us some insight what it is like to create such an event and also thanked the sponsors. There were some great prizes in the raffles or competitions like a 3D printer, a quadro-copter with video camera, few Raspberry Pis and also some elePHPants as is accustomed. Was not my lucky day as I did not win anything.</p>
<p>After the closing it was time for another social and some more bumper cars! Bumper cars were still fun and the BBQ food was really good. Enjoyed it a lot and made some new friends, so again it was a success.</p>
<h2 id="retrospective">Retrospective</h2>
<p>All in all, the trip was a great success in my mind and I really enjoyed it. There were great presentations and I learned a lot, I got some speaking experience and some good feedback from my UnCon talk and had lots of fun with existing and new friends. What more can you ask for?</p>
<p>I have only mentioned the talks I went to see, but there were many more. You can find all of the talks and slides for most of them through <a href="http://joind.in/event/view/1509">joind.in</a>. I think some of the talks were also filmed, so keep an eye out for videos later. Or you could also try googling for previous recordings as some of the talks have been presented before.</p>
<p>If you want to be a part of the PHP community, I can’t recommend enough that you attend the next PHP Benelux conference (and why not some others also if you haven’t already). The PHP community is so welcoming and there are so many great people it is really worth the time, money and effort. Already waiting for the next one, hope to see you there.<br />
-Carl.</p>
Fri, 31 Jan 2014 00:00:00 +0000http://cvuorinen.net/2014/01/cqrs-or-did-you-mean-bumper-cars-my-phpbenelux-2014-experience/
http://cvuorinen.net/2014/01/cqrs-or-did-you-mean-bumper-cars-my-phpbenelux-2014-experience/CommunityConferencePHPPHPBeneluxConferencesWhat's new in PHP 5.5<p>So, why another “PHP 5.5 new features” post? I was doing research on the subject for a tutorial at work so I was digging through all the resources I could find on the subject anyway, so I decided to write a post about it. And also because even though there are <a href="http://phpmaster.com/whats-new-in-php-5-5/">many</a> <a href="http://net.tutsplus.com/tutorials/php/what-to-expect-from-php-5-5/">great</a> <a href="http://evertpot.com/php-55-released/">posts</a> <a href="http://www.techrepublic.com/blog/software-engineer/10-improvements-in-php-550-for-web-developers/">already</a> on this topic, I found that none of them were that comprehensive to list all interesting changes that come with PHP 5.5. The PHP manual also has a quite comprehensive documentation about everything that has changed with PHP 5.5 <a href="http://www.php.net/manual/en/migration55.php">here</a>, but it is scattered across many pages with some not so relevant information (for most PHP devs) in there also. The official <a href="http://www.php.net/ChangeLog-5.php#5.5.0">ChangeLog</a> also lists everything that has changed, but it obviously does not go into that much detail on any of the topics.</p>
<!--more-->
<h2 id="generators">Generators</h2>
<p>I think the most discussed new feature has been generators. So, what generators actually are and what are they good for?</p>
<p>Generators look like normal functions or methods, except for the <strong>yield</strong> keyword. When calling yield the generator will return the given value to the caller but retain it’s state and continue where it left off when it is called next time. Generators also implement the <em>Iterator</em> interface, so they can be used with foreach loops for example. The usual examples given about generators are something like a replacement for PHP range() function or a Fibonacci number generator, I will not repeat them here (you can find these by reading some of the articles linked in this post), but instead present an equally useful example of a <a href="http://c2.com/cgi/wiki?FizzBuzzTest">FizzBuzz</a> implementation:</p>
<div class="language-php highlighter-rouge"><pre class="highlight"><code><span class="k">class</span> <span class="nc">FizzBuzz</span> <span class="p">{</span>
<span class="k">public</span> <span class="k">function</span> <span class="nf">printValues</span><span class="p">(</span><span class="nv">$num</span> <span class="o">=</span> <span class="mi">100</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">foreach</span> <span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getValues</span><span class="p">(</span><span class="nv">$num</span><span class="p">)</span> <span class="k">as</span> <span class="nv">$value</span><span class="p">)</span> <span class="p">{</span>
<span class="k">echo</span> <span class="nv">$value</span> <span class="o">.</span> <span class="nx">PHP_EOL</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">private</span> <span class="k">function</span> <span class="nf">getValues</span><span class="p">(</span><span class="nv">$num</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">for</span> <span class="p">(</span><span class="nv">$i</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="nv">$i</span> <span class="o">&lt;=</span> <span class="nv">$num</span><span class="p">;</span> <span class="nv">$i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
<span class="nv">$value</span> <span class="o">=</span> <span class="p">(</span><span class="nv">$i</span> <span class="o">%</span> <span class="mi">3</span><span class="p">)</span> <span class="o">?</span> <span class="s1">''</span> <span class="o">:</span> <span class="s1">'Fizz'</span><span class="p">;</span>
<span class="nv">$value</span> <span class="o">.=</span> <span class="p">(</span><span class="nv">$i</span> <span class="o">%</span> <span class="mi">5</span><span class="p">)</span> <span class="o">?</span> <span class="s1">''</span> <span class="o">:</span> <span class="s1">'Buzz'</span><span class="p">;</span>
<span class="k">yield</span> <span class="nv">$value</span> <span class="o">?:</span> <span class="nv">$i</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="nv">$fb</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">FizzBuzz</span><span class="p">();</span>
<span class="nv">$fb</span><span class="o">-&gt;</span><span class="na">printValues</span><span class="p">();</span>
</code></pre>
</div>
<p>One thing to keep in mind is that the <em>yield</em> keyword does not work the same way as the <em>return</em> keyword. The return value of calling a generator is actually an object of a PHP internal class called <em>Generator</em>. The <em>Generator</em> class implements the <em>Iterator</em> interface as already stated above, so this means that if you want to get values from a generator outside of a foreach loop, you will have to manually call the current() and next() methods on it (as defined by the interface).</p>
<p>I suppose generators will be used mainly as iterators with foreach, where the generator will be called for each iteration and the yielded value will then be available in the loop, like in the example above. The main benefit of using generators like this is that if you have large set of data that you need to iterate over, you do not have to create one huge array to hold all the data but instead you can process it one piece at the time to keep memory usage under control. Situations like this could be processing some large data set from a database or a file to generate reports or graphs for example. Another use case would be if you do not initially know how many records you need to process, so you can only yield as many as you need and then break out of the loop. Generators can effectively be used to create infinite data sets (like the Fibonacci sequence), although I could not come up with any valid real world use case for it (apart from some advanced maths). Sebastian Bergmann also has written a blog post about <a href="http://thephp.cc/viewpoints/blog/2013/07/php-5-5-generators">using Generators as Data Providers with PHPUnit</a>.</p>
<p>Generators also allow for two way communication between the calling code and the generator, i.e. you can send values back when the execution returns to the generator. This can be done by calling the send() method on the <em>Generator</em> instance. The sent value will be a “return” value of the yield expression. It is also possible to combine sending and receiving values within a generator with the same yield expression, but that could lead to some pretty hard to comprehend code quite easily. You can also throw exceptions <strong>into</strong> the generator in addition to throwing them <strong>from</strong> the generator. Throwing from the generator works as expected and the same way you normally throw an exception from a function or method. Throwing into the generator is done by calling the throw() method on the <em>Generator</em> object. You can then catch it inside the generator with a try-catch block around the yield.</p>
<p>Generators that you send data to can also be called <strong>coroutines</strong>, but that is a quite advanced topic and I will not cover it with anymore detail here, if you are interested to learn more about generators and coroutines, I suggest you read <a href="http://nikic.github.io/2012/12/22/Cooperative-multitasking-using-coroutines-in-PHP.html">this post</a> by Nikita Popov (developer of this feature in PHP core), the <a href="https://wiki.php.net/rfc/generators">RFC of generators</a> (also by Nikita Popov) and/or <a href="http://blog.ircmaxell.com/2012/07/what-generators-can-do-for-you.html">this post</a> by Anthony Ferrara (also a PHP core contributor).</p>
<h2 id="password-hashing-api">Password hashing API</h2>
<p>With version 5.5 PHP finally has an easy to use and secure password hashing API, which is a big deal security wise. This allows people that are not very experienced with hashing and cryptography to securely store passwords without having to learn some complicated stuff about salts, cost, stretching etc. If you have already been storing passwords securely by either doing it with your own code, or by using some third party library, this means from now on you can use the simple PHP password hashing API and not have to do it yourself or add any dependencies to do it.</p>
<p>Generating a secure hash is as simple as this:</p>
<div class="language-php highlighter-rouge"><pre class="highlight"><code><span class="nv">$hash</span> <span class="o">=</span> <span class="nb">password_hash</span><span class="p">(</span><span class="nv">$password</span><span class="p">,</span> <span class="nx">PASSWORD_DEFAULT</span><span class="p">);</span>
</code></pre>
</div>
<p>Under the hood the new password hashing API uses <strong>bcrypt</strong> for hashing and has automatic salting and also otherwise sane default values, so it is secure out of the box on most systems. There really is no reason to use any other hashing mechanism from now on in my opinion. Instead of using PASSWORD_DEFAULT, you can also specify the algorithm to use with PASSWORD_BCRYPT. Currently these are the only valid algorithms, but new ones will be added later as needed, and also the default algorithm may change in the future. An optional third parameter can also be used to provide some options for the hashing algorithm, such as salt and cost (for bcrypt). Note on the bcrypt cost parameter, it has a pretty good default value but it really is hardware dependent. So if you are worried about security, you should try what is a good cost value for your production hardware. An example script to do this can be found at the <a href="http://www.php.net/manual/en/function.password-hash.php#example-952">PHP manual page</a>.</p>
<p>To verify if a password is valid when a user logs in, it is equally simple:</p>
<div class="language-php highlighter-rouge"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span><span class="nb">password_verify</span><span class="p">(</span><span class="nv">$password</span><span class="p">,</span> <span class="nv">$hash</span><span class="p">))</span> <span class="p">{</span>
<span class="cm">/* Valid password */</span>
<span class="p">}</span>
<span class="k">else</span> <span class="p">{</span>
<span class="cm">/* Invalid password */</span>
<span class="p">}</span>
</code></pre>
</div>
<p>There is also a third function in this new API, called <em>password_needs_rehash</em>. This can be used to check if a password needs to be rehashed in case you have changed the options or hashing algorithm. With this functionality you can keep your software secure in the future as the hardware speeds increase you will eventually have to tweak the cost parameter, or change the algorithm entirely if a better one is introduced.</p>
<p>Here is an example of the usage:</p>
<div class="language-php highlighter-rouge"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span><span class="nb">password_needs_rehash</span><span class="p">(</span><span class="nv">$hash</span><span class="p">,</span> <span class="nv">$algorithm</span><span class="p">,</span> <span class="nv">$options</span><span class="p">))</span> <span class="p">{</span>
<span class="cm">/* Hash password with new algorithm or options */</span>
<span class="cm">/* Store the new hash */</span>
<span class="p">}</span>
</code></pre>
</div>
<p>If you are not yet ready to upgrade to PHP 5.5, but you like the new password hashing API and would like to use it in your application right now, there is a library that you can use for just this purpose called <a href="https://github.com/ircmaxell/password_compat">password_compat</a>. It has the same API as the official PHP 5.5 implementation and it was created by the same developer as the PHP core implementation (Anthony Ferrara). This means that you can use it as long as your app is running with PHP version below 5.5, and when you upgrade to 5.5 it will start using the PHP core implementation automatically and you can remove the dependency to password_compat.</p>
<p>One thing to note is that if you use the PASSWORD_DEFAULT algorithm option, it is recommended to use VARCHAR(255) to store the hashes and not limit the size to current bcrypt hash size explicitly. This is to avoid issues in the future if the default algorithm is changed to something that creates longer hashes.</p>
<h2 id="opcache">OPCache</h2>
<p>PHP 5.5 has a built-in Opcode cache called <a href="http://php.net/manual/en/book.opcache.php">OPcache</a>. It is actually the previously called Zend Optimizer+ that was closed source software, but Zend open sourced it to be included in PHP core. An opcode cache increases performance of PHP applications with zero effort on the application side (by storing precompiled bytecode in shared memory so scripts will not have to be parsed on each request), i.e. you get faster app without doing anything. That is a no-brainer and also the reason you should be using an opcode cache even if you are still running some previous version of PHP. The OPcache extension can be installed as an extension to older PHP versions too, or you can of course use APC.</p>
<p>Even though OPcache is built-in with PHP 5.5 (compiled by default with PHP), it is not enabled by default so you will need to enable it. This can be done by simply editing the php.ini file as described <a href="http://www.php.net/manual/en/opcache.installation.php">in the manual</a>. The way that different repositories for popular Linux distributions handle the installation/enabling this extension remains to be seen, it might be enabled by default or it might need to be enabled separately by installing some other package like php-opcache etc.</p>
<p>Performance wise the new Zend Optimizer+ has been a little bit better than APC. Here is a benchmark chart with PHP 5.5 without any opcode cache, with APC and with OPcache (generated from <a href="http://bit.ly/116BnnB">this chart</a> that was linked in the <a href="https://wiki.php.net/rfc/optimizerplus">RFC of OPcache</a>)</p>
<div class="alignnone" style="width: 300px;">
<a href="/assets/images/2013/08/chart_1.png"><img src="/assets/images/2013/08/chart_1-300x156.png" width="300" /></a>
<p class="caption">PHP Opcode cache benchmark</p>
</div>
<p> </p>
<p>If you have been using APC’s data caching API you can use the <a href="https://github.com/krakjoe/apcu">APCu</a> (short for APC user cache) that is a fork of APC with the opcode cache functionality removed. It is still in beta but a stable version should be available soon.</p>
<p>Something that you might need to consider when enabling OPcache is your deployment strategy. OPcache does not use inodes as keys in the shared memory (like APC), but instead it is realpath based. This means that if you override a file, it will start using the updated file immediately. This causes a situation where a running script might start execution on your old code base but start using files from a new code base in the middle of request if deployment happened at the same time. Whether or not you have to worry about situations like these depends on how much traffic your site/application has, how often you deploy, how critical the application is etc. so it’s really up to you to decide. This issue can be handled in many ways, Rasmus Lerdorf has posted a quite detailed description how they <a href="http://codeascraft.com/2013/07/01/atomic-deploys-at-etsy/">handle deploys atomically at Etsy</a> by using a symlinked document root directory and a custom Apache module and PHP extension to resolve the symlink.</p>
<h2 id="finally">Finally</h2>
<p>Finally there is… <em>finally</em>. The new <em>finally</em> keyword can be used with a try-catch block to execute certain code regardless if an exception was thrown or not. Actually you don’t even need the <em>catch</em> part, you can put <em>finally</em> after <em>try</em> if you are not anticipating any exceptions but want to make sure that some code is run even if an uncatched exception is thrown.</p>
<p>Here is a small example:</p>
<div class="language-php highlighter-rouge"><pre class="highlight"><code><span class="nv">$db</span> <span class="o">=</span> <span class="nb">mysqli_connect</span><span class="p">();</span>
<span class="k">try</span> <span class="p">{</span>
<span class="c1">//the function may throw exceptions which we can not handle
</span> <span class="nx">call_some_function</span><span class="p">(</span><span class="nv">$db</span><span class="p">);</span>
<span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="nx">SomeException</span> <span class="nv">$e</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">error</span><span class="p">(</span><span class="nv">$e</span><span class="p">);</span>
<span class="p">}</span> <span class="nx">finally</span> <span class="p">{</span>
<span class="nx">mysqli_close</span><span class="p">(</span><span class="nv">$db</span><span class="p">);</span>
<span class="p">}</span>
</code></pre>
</div>
<p>In the example above, the code inside the finally block will be called in all of these situations:</p>
<ol>
<li>The call to call_some_function() executes successfully without throwing any exceptions.</li>
<li>An exception of type SomeException is thrown and catched and the code inside the catch block is executed.</li>
<li>An uncaught exception is thrown.</li>
</ol>
<p>So the <em>finally</em> is quite useful in case you need some code to execute regardless of what happens. The obvious use cases for this are things like cleanup, close resource handles like file pointers and external connections.</p>
<h2 id="list-in-foreach">list() in foreach</h2>
<p>Foreach now supports the use of list() that allows easier handling of nested arrays. Basically you can map the elements from the second level array into variables, all in the foreach statement itself.</p>
<p>Maybe an example will demonstrate this better, so here is a small script that iterates over some csv data:</p>
<div class="language-php highlighter-rouge"><pre class="highlight"><code><span class="nv">$csvData</span> <span class="o">=</span> <span class="s1">'1;Foo;bar
2;baz;
5;Lorem;ipsum'</span><span class="p">;</span>
<span class="k">foreach</span> <span class="p">(</span><span class="nx">parseCsv</span><span class="p">(</span><span class="nv">$csvData</span><span class="p">)</span> <span class="k">as</span> <span class="k">list</span><span class="p">(</span><span class="nv">$id</span><span class="p">,</span> <span class="nv">$name</span><span class="p">,</span> <span class="nv">$type</span><span class="p">))</span> <span class="p">{</span>
<span class="k">echo</span> <span class="s1">'Id: '</span> <span class="o">.</span> <span class="nv">$id</span> <span class="o">.</span> <span class="s2">"</span><span class="se">\t</span><span class="s2">"</span>
<span class="o">.</span> <span class="s1">'Name: '</span> <span class="o">.</span> <span class="nv">$name</span> <span class="o">.</span> <span class="s2">"</span><span class="se">\t</span><span class="s2">"</span>
<span class="o">.</span> <span class="s1">'Type: '</span> <span class="o">.</span> <span class="nv">$type</span> <span class="o">.</span> <span class="s2">"</span><span class="se">\n</span><span class="s2">"</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">function</span> <span class="nf">parseCsv</span><span class="p">(</span><span class="nv">$csv</span><span class="p">,</span> <span class="nv">$separator</span> <span class="o">=</span> <span class="s1">';'</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">foreach</span> <span class="p">(</span><span class="nb">explode</span><span class="p">(</span><span class="s2">"</span><span class="se">\n</span><span class="s2">"</span><span class="p">,</span> <span class="nv">$csv</span><span class="p">)</span> <span class="k">as</span> <span class="nv">$csvLine</span><span class="p">)</span> <span class="p">{</span>
<span class="k">yield</span> <span class="nb">str_getcsv</span><span class="p">(</span><span class="nb">trim</span><span class="p">(</span><span class="nv">$csvLine</span><span class="p">),</span> <span class="nv">$separator</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre>
</div>
<p>The output from this script would be:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>Id: 1 Name: Foo Type: bar
Id: 2 Name: baz Type:
Id: 5 Name: Lorem Type: ipsum
</code></pre>
</div>
<p>The main use cases for this would be looping over nested arrays where the second level array always has the same known structure. So something like looping over SQL result sets or csv file data come to mind first. It doesn’t really matter where the data comes from, as long as it is in this kind of tabular format where you have any number of “rows” and each row contains same “columns”. You can then use this syntax to avoid using something like <em>$row[1]</em> that really has no meaning as to what data it holds.</p>
<h2 id="emptyanything">empty(anything)</h2>
<p>The empty() call (language construct, not a function) now supports arbitrary expressions, which means “just about anything you can throw at it” in more common terms, including function and method calls. Yay for this! No more “PHP Fatal error: Can’t use function return value in write context…”. It’s about time this finally works the way that everyone not knowing any better expects it to work.</p>
<p>Here are a few examples:</p>
<div class="language-php highlighter-rouge"><pre class="highlight"><code><span class="nb">var_dump</span><span class="p">(</span><span class="k">empty</span><span class="p">(</span><span class="s2">"foo"</span><span class="p">));</span> <span class="c1">// false
</span>
<span class="nb">var_dump</span><span class="p">(</span><span class="k">empty</span><span class="p">(</span><span class="nv">$foo</span><span class="p">));</span> <span class="c1">// true
</span>
<span class="nv">$bar</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
<span class="nb">var_dump</span><span class="p">(</span><span class="k">empty</span><span class="p">(</span><span class="nv">$bar</span><span class="p">));</span> <span class="c1">// false
</span>
<span class="nb">var_dump</span><span class="p">(</span><span class="k">empty</span><span class="p">(</span><span class="o">--</span><span class="nv">$bar</span><span class="p">));</span> <span class="c1">// true
</span>
<span class="k">function</span> <span class="nf">foo</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>
<span class="nb">var_dump</span><span class="p">(</span><span class="k">empty</span><span class="p">(</span><span class="nx">foo</span><span class="p">()));</span> <span class="c1">// false
</span>
<span class="k">class</span> <span class="nc">Foo</span> <span class="p">{</span>
<span class="k">const</span> <span class="no">CLASS_CONSTANT</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
<span class="k">public</span> <span class="k">function</span> <span class="nf">bar</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">public</span> <span class="k">static</span> <span class="k">function</span> <span class="nf">baz</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="kc">null</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="nv">$foo</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Foo</span><span class="p">();</span>
<span class="nb">var_dump</span><span class="p">(</span><span class="k">empty</span><span class="p">(</span><span class="nv">$foo</span><span class="o">-&gt;</span><span class="na">bar</span><span class="p">()));</span> <span class="c1">// true
</span>
<span class="nb">var_dump</span><span class="p">(</span><span class="k">empty</span><span class="p">(</span><span class="nx">Foo</span><span class="o">::</span><span class="na">CLASS_CONSTANT</span><span class="p">));</span> <span class="c1">// false
</span>
<span class="nb">var_dump</span><span class="p">(</span><span class="k">empty</span><span class="p">(</span><span class="nx">Foo</span><span class="o">::</span><span class="na">baz</span><span class="p">()));</span> <span class="c1">// true
</span>
<span class="nb">var_dump</span><span class="p">(</span><span class="k">empty</span><span class="p">(</span><span class="k">function</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span> <span class="p">}));</span> <span class="c1">// false
</span>
<span class="nv">$func</span> <span class="o">=</span> <span class="k">function</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span><span class="p">;</span> <span class="p">};</span>
<span class="nb">var_dump</span><span class="p">(</span><span class="k">empty</span><span class="p">(</span><span class="nv">$func</span><span class="p">()));</span> <span class="c1">// true
</span>
<span class="nv">$x</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
<span class="nv">$y</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span>
<span class="nb">var_dump</span><span class="p">(</span><span class="k">empty</span><span class="p">(</span><span class="nv">$x</span> <span class="o">+</span> <span class="nv">$y</span><span class="p">));</span> <span class="c1">// false
</span>
<span class="nb">var_dump</span><span class="p">(</span><span class="k">empty</span><span class="p">(</span><span class="mi">2</span> <span class="o">-</span> <span class="mi">2</span><span class="p">));</span> <span class="c1">// true
</span></code></pre>
</div>
<h2 id="array_column">array_column()</h2>
<p>The new array_column() function is a convenient way to get a single column of data from a multidimensional array. Similar to PDOStatement::fetchColumn() and what other database access layers provide for database record retrieval, array_column() can do the same in PHP. Nothing that special about it, you can do the same yourself quite easily, it’s just convenient to have it in the core and might be useful in many situations. You can also select what column you want to use as the index of the returned array by providing it as a third parameter.</p>
<p>Here is a small example:</p>
<div class="language-php highlighter-rouge"><pre class="highlight"><code><span class="nv">$array</span> <span class="o">=</span> <span class="p">[</span>
<span class="p">[</span>
<span class="s1">'id'</span> <span class="o">=&gt;</span> <span class="mi">2135</span><span class="p">,</span>
<span class="s1">'first_name'</span> <span class="o">=&gt;</span> <span class="s1">'John'</span><span class="p">,</span>
<span class="s1">'last_name'</span> <span class="o">=&gt;</span> <span class="s1">'Doe'</span>
<span class="p">],</span>
<span class="p">[</span>
<span class="s1">'id'</span> <span class="o">=&gt;</span> <span class="mi">3245</span><span class="p">,</span>
<span class="s1">'first_name'</span> <span class="o">=&gt;</span> <span class="s1">'Sally'</span><span class="p">,</span>
<span class="s1">'last_name'</span> <span class="o">=&gt;</span> <span class="s1">'Smith'</span>
<span class="p">],</span>
<span class="p">[</span>
<span class="s1">'id'</span> <span class="o">=&gt;</span> <span class="mi">5342</span><span class="p">,</span>
<span class="s1">'first_name'</span> <span class="o">=&gt;</span> <span class="s1">'Jane'</span><span class="p">,</span>
<span class="s1">'last_name'</span> <span class="o">=&gt;</span> <span class="s1">'Jones'</span>
<span class="p">],</span>
<span class="p">];</span>
<span class="nv">$names</span> <span class="o">=</span> <span class="nb">array_column</span><span class="p">(</span><span class="nv">$array</span><span class="p">,</span> <span class="s1">'first_name'</span><span class="p">);</span>
<span class="nb">print_r</span><span class="p">(</span><span class="nv">$names</span><span class="p">);</span>
<span class="nv">$namesById</span> <span class="o">=</span> <span class="nb">array_column</span><span class="p">(</span><span class="nv">$array</span><span class="p">,</span> <span class="s1">'last_name'</span><span class="p">,</span> <span class="s1">'id'</span><span class="p">);</span>
<span class="nb">print_r</span><span class="p">(</span><span class="nv">$namesById</span><span class="p">);</span>
</code></pre>
</div>
<p>And the output from that would be:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>Array
(
[0] =&gt; John
[1] =&gt; Sally
[2] =&gt; Jane
)
Array
(
[2135] =&gt; Doe
[3245] =&gt; Smith
[5342] =&gt; Jones
)
</code></pre>
</div>
<p>The author of this function, Ben Ramsey, has also released a small <a href="https://github.com/ramsey/array_column">userland library</a> that you can use with previous versions of PHP if you can’t update right away but want to use it.</p>
<h2 id="class">::class</h2>
<p>A new <em>::class</em> syntax allows the retrieval of the fully qualified class name of any namespaced classes that have been imported/aliased with a <em>use</em> statement.</p>
<p>Here is a simple example:</p>
<div class="language-php highlighter-rouge"><pre class="highlight"><code><span class="k">use</span> <span class="nx">Some\Really\Long\Namespacing\AndAlsoQuiteLongClassName</span> <span class="k">as</span> <span class="nx">Foo</span><span class="p">;</span>
<span class="k">echo</span> <span class="s1">'Foo: '</span> <span class="o">.</span> <span class="nx">Foo</span><span class="o">::</span><span class="na">class</span><span class="p">;</span>
</code></pre>
</div>
<p>And it will output:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>Foo: Some\Really\Long\Namespacing\AndAlsoQuiteLongClassName
</code></pre>
</div>
<p>It is quite handy so you will not have to type (or copy-paste) the fully qualified class names around when you already have the class imported/aliased with a use statement.</p>
<p>The main use cases for this are any implementations where you have to provide a class name as a string. Some examples are PHPUnit’s mock builder, Doctrine entity manager, PHP’s built in reflection API and also with PHP functions such as <code class="highlighter-rouge">class_exists()</code> and <code class="highlighter-rouge">is_subclass_of()</code> etc. I think I will personally be using this most with the Doctrine entity manager since I am currently working with a Symfony project, and I am quite looking forward to using it since it is quite annoying to have to repeat the whole namespace every time like this: <code class="highlighter-rouge">$this-&gt;em-&gt;getRepository('Acme\\DemoBundle\\Entity\\SomeEntity');</code> when you could just write <code class="highlighter-rouge">$this-&gt;em-&gt;getRepository(Entity\SomeEntity::class);</code> if you have a use statement like this: <code class="highlighter-rouge">use Acme\DemoBundle\Entity;</code></p>
<p>The ::class syntax also works with other existing OOP keywords, such as <em>self</em>, <em>static</em> and <em>parent,</em> for example: <code class="highlighter-rouge">self::class</code> and <code class="highlighter-rouge">parent::class</code>. Although this does not provide any new functionality since you can get the equivalent of those in previous PHP versions with <code class="highlighter-rouge">__CLASS__</code> and <code class="highlighter-rouge">get_parent_class()</code>, the new syntax is cleaner and more consistent so it’s a pretty nice thing in my opinion.</p>
<h2 id="datetimeimmutable">DateTimeImmutable</h2>
<p>The new <em>DateTimeImmutable</em> class allows creating <em>DateTime</em> like objects that cannot be modified. This is mainly useful when using a single <em>DateTime</em> object multiple times, for example passing it as a parameter to other methods, performing calculations on it or displaying it in another timezone. Using <em>DateTimeImmutable</em> means you will not have to worry about whether the object has been changed somewhere along the way or not.</p>
<p>The <em>DateTimeImmutable</em> works <em>almost</em> just like regular <em>DateTime</em>, but there are a few gotchas. First one is that DateTimeImmutable does not inherit from DateTime so if you have a method that requires a DateTime object, you can not give it a DateTimeImmutable. The other thing is that, as stated before, DateTimeImmutable cannot be modified, but it returns a new object instead. The regular DateTime object returns $this to allow method chaining, but if you are not chaining anything you can just call a method to change the object, like for example <code class="highlighter-rouge">$date-&gt;modify('+1 day')</code>. With DateTimeImmutable you can also call it the same way but that will not change anything, you will have to assign the return value to a variable and that will be a new object and not the original, so the example would have to be changed to <code class="highlighter-rouge">$date = $date-&gt;modify('+1 day')</code>.</p>
<h2 id="array-and-string-dereferencing">Array and String Dereferencing</h2>
<p>Constant array and string dereferencing, also known as constructor dereferencing and literal dereferencing, basically allows plucking one element from an array or one letter from a string right when creating the array or string. Again an example illustrates this better than any words I can come up with:</p>
<div class="language-php highlighter-rouge"><pre class="highlight"><code><span class="k">echo</span> <span class="k">array</span><span class="p">(</span><span class="s1">'Foo'</span><span class="p">,</span> <span class="s1">'Bar'</span><span class="p">,</span> <span class="s1">'Baz'</span><span class="p">)[</span><span class="mi">1</span><span class="p">]</span> <span class="o">.</span> <span class="nx">PHP_EOL</span><span class="p">;</span> <span class="c1">// Output: Bar
</span>
<span class="k">echo</span> <span class="s1">'abc'</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span> <span class="o">.</span> <span class="nx">PHP_EOL</span><span class="p">;</span> <span class="c1">// Output: c
</span></code></pre>
</div>
<p>You can of course use a variable at the referencing part (inside the brackets), which is kind of the only way this feature would make any sense. Although I still have a hard time coming up with any real world use cases for this. As I understand, the main reason behind implementing this feature was “because some other languages have it”. So I guess there are some use cases for this out there.</p>
<h2 id="gd-improvements">GD improvements</h2>
<p>There are a few improvements to the GD image manipulation extension. Support for image flipping and cropping with functions imageflip(), imagecrop() and imagecropauto(). Support for reading and creating WebP images was also added with functions imagecreatefromwebp() and imagewebp().</p>
<h2 id="other-misc-new-featuresfunctions">Other misc new features/functions</h2>
<p>Here is a list of some other miscellaneous new features and functions that I will not cover here with any more details.</p>
<ul>
<li>Non-scalar Iterator keys in foreach</li>
<li>Apache 2.4 support on Windows</li>
<li><a href="http://php.net/manual/en/function.boolval.php">boolval()</a> - Get the boolean value of a variable</li>
<li><a href="http://www.php.net/manual/en/function.cli-set-process-title.php">cli_set_process_title()</a> - Set PHP CLI process’ title that’s visible in top or ps</li>
<li><a href="http://www.php.net/manual/en/function.hash-pbkdf2.php">hash_pbkdf2()</a> - Generate a PBKDF2 key derivation of a supplied password</li>
<li><a href="http://www.php.net/manual/en/class.curlfile.php">CURLFile</a> - cURL file upload class</li>
<li><a href="http://www.php.net/manual/en/class.intlcalendar.php">IntlCalendar</a></li>
</ul>
<h2 id="deprecations-and-other-removals">Deprecations and other removals</h2>
<p>With all the great new stuff, also some old have been cleaned out. Here is a list of the most notable deprecations and removals:</p>
<ul>
<li>ext/mysql deprecated. This means that from now on when connecting to a database an E_DEPRECATED error will be generated. It can still be used for now, but it is advisable to use mysqli or PDO instead.</li>
<li>Dropped Windows XP and 2003 support. Yea. Anybody still running modern PHP apps on those?</li>
<li>preg_replace() /e modifier deprecated. preg_replace_callback() can be used instead.</li>
<li>Logo GUIDs removed i.e. php_logo_guid() and zend_logo_guid()</li>
</ul>
<p>I have tried to cover most of the relevant stuff here. You can check a more comprehensive list of all the little things that have changed at the <a href="http://www.php.net/manual/en/migration55.php">PHP manual migration guide</a>. Both new and removed.</p>
<h2 id="conclusion">Conclusion</h2>
<p>PHP 5.5 has quite a lot of new and handy features and also a lot of nice little additions/modifications to existing features that make our lives as PHP developers a little bit easier. When doing the research about these new features for the tutorial and this blog post, I have come to the conclusion that the PHP RFCs (Request For Comments) is a really good place to learn about the new stuff. They often offer quite a lot of background about the changes or the new feature and almost always also give some real world use cases for them. Nikita Popov has put up a nice <a href="https://gist.github.com/nikic/5213689">list of new features in PHP 5.5</a> that links to their respective RFCs. This has been really helpful and I have learned a lot when reading those. From now on I think I will always check the RFCs of the new features when a new version of PHP comes out.</p>
<p>This post turned out to be quite long, if you have read all the way here, hopefully you have learned something new. The next step is to try these out by yourself. I know I learned a lot by playing around with these new features. If you are familiar with Vagrant, you can have a virtual machine up and running with PHP 5.5 in just a few minutes, for example by using the awesome <a href="https://puphpet.com/">PuPHPet</a> service where you can configure the VM on the website really easily.</p>
Sun, 04 Aug 2013 00:00:00 +0000http://cvuorinen.net/2013/08/whats-new-in-php-5-5/
http://cvuorinen.net/2013/08/whats-new-in-php-5-5/PHPProgrammingInstalling SonarQube with Jenkins integration for a PHP project<p>In this second part of my Continous Integration setup I will detail the steps required to install SonarQube (previously called just Sonar, renamed to SonarQube with 3.6 release just a few days ago) and integrate it with the Jenkins server from the <a href="http://cvuorinen.net/2013/06/installing-jenkins-ci-server-with-github-integration-for-a-php-project/">previous post</a> so SonarQube will run a daily analysis of our PHP project. In the previous post I covered the installation of Jenkins on a CentOS server and integrated it with GitHub, so if you do not have Jenkins set up you might want to start <a href="http://cvuorinen.net/2013/06/installing-jenkins-ci-server-with-github-integration-for-a-php-project/">there</a>.</p>
<!--more-->
<p>So why do we need Sonar if Jenkins is already setup with all the static code analysis reports as in the “<a href="http://jenkins-php.org/">Template for Jenkins Jobs for PHP Projects</a>” ? Jenkins is great for running builds and it can be setup in a way that it generates useful reports about the source code, but Sonar has been specifically designed for this. It has a great user interface and gives so much better statistics. You can really easily see what direction the project is going and how much technical debt you are accumulating. You can drill down to different parts of the project and compare them, you can see how the code base has changed over time and compare different versions etc. This is especially useful with large projects that have a long lifespan so you can better keep track of code quality. You can also take action on the issues Sonar has found by assigning them to people. All the dashboards are customizable with loads of different widgets and all the widgets are also customizable so you can really make it your own and make the data that you care about the most easily accessible. SonarQube really takes the “static” out of static code analysis and makes it dynamic and interactive. You have to see it in action to really experience it, so I suggest you either watch a <a href="http://www.sonarqube.org/sonar-tv-a-short-video-for-every-key-feature/">screencast</a> or click around in the <a href="http://nemo.sonarsource.org/">live demo</a>.</p>
<h2 id="installing-sonarqube">Installing SonarQube</h2>
<p>First, install SonarQube using yum by running these commands:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>$ sudo wget -O /etc/yum.repos.d/sonar.repo http://downloads.sourceforge.net/project/sonar-pkg/rpm/sonar.repo
$ yum install sonar
</code></pre>
</div>
<p>Although this post focuses on CentOS installation, you can find <a href="http://sonar-pkg.sourceforge.net/">packages for most popular Linux distributions</a>.</p>
<p>Next we have to edit the Sonar config file <em>/opt/sonar/conf/sonar.properties</em> to change the db to MySQL. You can of course use whatever database you like, but I had MySQL already installed on the machine so it was an obvious choice. Just comment out the line about the embedded H2 database (which is not intended for production use) and uncomment the MySQL line, save and exit. After that you also have to create an empty database called sonar and create a user named sonar that has access to the database.</p>
<p>This can be done by running the following commands on mysql:</p>
<div class="language-sql highlighter-rouge"><pre class="highlight"><code><span class="k">CREATE</span> <span class="k">DATABASE</span> <span class="n">sonar</span> <span class="n">CHARACTER</span> <span class="k">SET</span> <span class="n">utf8</span> <span class="k">COLLATE</span> <span class="n">utf8generalci</span><span class="p">;</span>
<span class="k">CREATE</span> <span class="k">USER</span> <span class="s1">'sonar'</span> <span class="n">IDENTIFIED</span> <span class="k">BY</span> <span class="s1">'sonar'</span><span class="p">;</span>
<span class="k">GRANT</span> <span class="k">ALL</span> <span class="k">ON</span> <span class="n">sonar</span><span class="p">.</span><span class="o">*</span> <span class="k">TO</span> <span class="s1">'sonar'</span><span class="o">@</span><span class="s1">'%'</span> <span class="n">IDENTIFIED</span> <span class="k">BY</span> <span class="s1">'sonar'</span><span class="p">;</span>
<span class="k">GRANT</span> <span class="k">ALL</span> <span class="k">ON</span> <span class="n">sonar</span><span class="p">.</span><span class="o">*</span> <span class="k">TO</span> <span class="s1">'sonar'</span><span class="o">@</span><span class="s1">'localhost'</span> <span class="n">IDENTIFIED</span> <span class="k">BY</span> <span class="s1">'sonar'</span><span class="p">;</span>
<span class="n">FLUSH</span> <span class="k">PRIVILEGES</span><span class="p">;</span>
</code></pre>
</div>
<p>I also had to change the default port of Sonar since I had Nginx with PHP running on the same server and php-fpm was already using port 9000 (which I discovered after Sonar refused to start and I had to take a look at the Sonar log file in <em>/opt/sonar/logs/sonar.log</em>). So I changed Sonar to use port 9090 (in the Sonar config file).</p>
<p>After that you can go ahead and start Sonar using the following command:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>$ sudo service sonar start
</code></pre>
</div>
<p>Note, do not use the script in /opt/sonar/bin… to start Sonar (instructed in Sonar documentation) as root user because you will run into file permission issues later since the init.d script runs it as the user “sonar” (I had to learn this the hard way, so just trying to save you the trouble).</p>
<p>If you have a firewall that blocks access by default, you may need to open the port 9000 (or 9090 if you had to change the port like me) to be able to access Sonar from outside. We had iptables running so I just added a rule to allow 9090 and restarted iptables.</p>
<p>If everything went fine, SonarQube should be running and we can point a browser to: http://serverAddress:9000 (or http://serverAddress:9090 in my case).</p>
<h2 id="securing-sonar">Securing Sonar</h2>
<p>You can log in with the default account “admin” with password “admin”. The first thing you should do is of course change the password on the page under “Administrator” &gt; “My Account”. After that you can disable access from anonymous users in the “Settings” &gt; “Configuration” &gt; “Security” page by selecting True in the “Force user authentication” setting.</p>
<h2 id="installing-sonarqube-runner">Installing SonarQube Runner</h2>
<p>Installation instructions can be found here: <a href="http://docs.codehaus.org/display/SONAR/Installing+and+Configuring+SonarQube+Runner">http://docs.codehaus.org/display/SONAR/Installing+and+Configuring+SonarQube+Runner</a></p>
<p>First download and uncompress the file (check the above link for the latest version) and create a symbolic link to this specific version by executing the following commands:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>$ cd /opt
$ sudo wget http://repo1.maven.org/maven2/org/codehaus/sonar/runner/sonar-runner-dist/2.2.2/sonar-runner-dist-2.2.2.zip
$ sudo unzip sonar-runner-dist-2.2.2.zip
$ sudo ln -s sonar-runner-2.2.2 sonar-runner
</code></pre>
</div>
<p>Next we need to edit the configuration file and update database information and server URL. In our case the file is <em>/opt/sonar-runner/conf/sonar-runner.properties</em> and you need to set the correct sonar.host.url, uncomment the line for MySQL as the database, uncomment the database username and password. You will also have to uncomment and update the login details if you selected the “Force user authentication” setting in the previous section.</p>
<p>Next we need to create a new environment variable called SONAR_RUNNER_HOME and add the sonar runner bin directory to the PATH environment variable, this can be done with the following command:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>$ sudo echo -e '#!/bin/bash\nexport SONAR_RUNNER_HOME=/opt/sonar-runner\nexport PATH=$PATH:$SONAR_RUNNER_HOME/bin' &gt; /etc/profile.d/sonar-runner.sh
</code></pre>
</div>
<p>And if you don’t want to log out and back in again for this to take effect, you can run these commands to add the environment variables for the current session:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>$ export SONAR_RUNNER_HOME=/opt/sonar-runner
$ export PATH=$PATH:$SONAR_RUNNER_HOME/bin
</code></pre>
</div>
<p>Now the runner has been installed, and you can test it by executing this command:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>$ sonar-runner -v
</code></pre>
</div>
<p>If everything worked correctly, you should receive the Sonar Runner version number as output.</p>
<h2 id="installing-php-environment-for-sonarqube">Installing PHP environment for SonarQube</h2>
<p>SonarQube relies on some external tools for PHP analysis, so we need to make sure everything is installed on our system and also install the PHP plugin for Sonar. SonarQube requires PHP Depend, PHPMD, PHP_CodeSniffer and PHPUnit which you already might have installed on your system if you followed my previous post and installed these for the build tasks. If not, check <a href="http://phpqatools.org/">http://phpqatools.org/</a> for a quick install of everything in one command. SonarQube also requires Xdebug, so we will need to install that with the following command:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>$ yum install php-pecl-xdebug
</code></pre>
</div>
<p>Next log into SonarQube and head to “Settings” &gt; “System” &gt; “Update Center”. Click “Available Plugins” and click “PHP” in the list of available languages and then click Install. After that we need to restart Sonar by executing the following command:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>$ sudo service sonar restart
</code></pre>
</div>
<h2 id="integrating-sonarqube-with-jenkins">Integrating SonarQube with Jenkins</h2>
<p>Now that we have SonarQube all set up, it’s time to integrate code analysis with our Continuous Integration set up from the <a href="http://cvuorinen.net/2013/06/installing-jenkins-ci-server-with-github-integration-for-a-php-project/">previous post</a>. For this we need to go back to Jenkins and install the SonarQube Jenkins Plugin. Log into Jenkins as administrator and go to “Manage Jenkins” &gt; “Manage Plugins”, click the “Available” tab and type “sonar” to the filter input in the top right, select Jenkins Sonar Plugin and install it and restart Jenkins.</p>
<p>Then we need to tell Jenkins where our Sonar installation is, so head on to “Manage Jenkins” &gt; “Configure System” and find the “Sonar Runner” section and click “Add Sonar Runner”. Give your Sonar Runner a name (I called mine “Default”) and point it to the SONAR_RUNNER_HOME directory (<em>/opt/sonar-runner</em>). Then find the “Sonar” section and click “Add Sonar”. Give your Sonar installation a name (I called mine “SonarQube”), click “Advanced” and fill in your server URL, login account and database details. Finally hit Save.</p>
<p>Next create a file called <em>sonar-project.properties</em> in the root directory the project you want to analyse with SonarQube. This file is needed to configure the SonarQube Runner. You can find an example file for a PHP project here: <a href="https://github.com/SonarSource/sonar-examples/blob/master/projects/languages/php/php-sonar-runner-unit-tests/sonar-project.properties">https://github.com/SonarSource/sonar-examples/blob/master/projects/languages/php/php-sonar-runner-unit-tests/sonar-project.properties</a>. Set the properties according to your project and save and commit.</p>
<p>Now we need to add a build step to run Sonar analysis on each build. Open the project in Jenkins and click “Configure” on the left sidebar. Scroll down to the “Build” section and click “Add build step” and select “Invoke Standalone Sonar Analysis”. If you used the default name and location for the <em>sonar-project.properties</em> file, you will not have to specify it’s path. In case you selected the “Force user authentication” setting when securing Sonar, you will have to provide login credentials for the runner. This can be done in the “Project properties” text input field by setting the sonar.login and sonar.password properties (not sure if this is really required since they are already in the Sonar runner configuration file, but I added them anyway). Then Save.</p>
<p>Now everything is set up and you can try it out by running a build.</p>
<h2 id="optimizing-and-finishing-up">Optimizing and finishing up</h2>
<p>Since Jenkins was already running all the static code analysis with PHPMD, PHP Depend and PHP_CodeSniffer etc. in my Ant build, there really is no need for Sonar to run the same stuff again. Luckily there are properties that you can set in the <em>sonar-project.properties</em> file to disable generating the reports again and only analyze existing reports. More details can be found here: <a href="http://docs.codehaus.org/display/SONAR/PHP+Plugin#PHPPlugin-Reusingexistingreports">http://docs.codehaus.org/display/SONAR/PHP+Plugin#PHPPlugin-Reusingexistingreports</a></p>
<p>Another thing is that if you have the <em>failonerror</em> parameter in the Ant <em>build.xml</em> file set to “true” for unit tests, Jenkins will not run Sonar at all if any tests fail, since the build already failed in the first step. So I removed the attribute because it really is not needed, at least not in my case since I have the “XUnit test results report” Post-build action configured (from the <a href="http://jenkins-php.org/">Template for Jenkins Jobs for PHP Projects</a>) and it will mark the build as failed when there are failed unit tests, but the good thing in this case is that it will do so only after all the build steps have been executed, allowing Sonar runner to run as well.</p>
Mon, 08 Jul 2013 00:00:00 +0000http://cvuorinen.net/2013/07/installing-sonarqube-with-jenkins-integration-for-a-php-project/
http://cvuorinen.net/2013/07/installing-sonarqube-with-jenkins-integration-for-a-php-project/Continuous IntegrationPHPSonarSonarQubeWeb DevelopmentInstalling Jenkins CI server with GitHub integration for a PHP project<p>Here are the details how to install Jenkins CI server on a CentOS server (version 6.4 in this case) and set it up with GitHub integration so pushing to GitHub automatically triggers a build. Our project is a PHP project so the build will have PHP related stuff and we are going to use Ant as the build system.</p>
<!--more-->
<h2 id="install-jenkins">Install Jenkins</h2>
<p>First open <a href="https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+on+RedHat+distributions">https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+on+RedHat+distributions</a> for installation instructions, here are the relevant points in short;
Check java version by running:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>$ java -version
</code></pre>
</div>
<p>If you have the OpenJDK version you are good to go (I did). If not, follow instructions in the page linked above to install a compatible Java runtime.</p>
<p>Then it’s time to proceed with the Jenkins install. Just add the Jenkins repo and install it with yum by running these commands:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>$ sudo wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins-ci.org/redhat/jenkins.repo
$ sudo rpm --import http://pkg.jenkins-ci.org/redhat/jenkins-ci.org.key
$ sudo yum install jenkins
</code></pre>
</div>
<p>And it’s done. Then start Jenkins by running the command:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>$ sudo service jenkins start
</code></pre>
</div>
<p>If you have a firewall that blocks access by default, you may need to open the port 8080 to be able to access Jenkins. We had iptables running so I just added a rule to allow 8080 and restarted iptables. Done.</p>
<p>Next you can check that Jenkins is running by pointing a browser to http://serverAddress:8080</p>
<p>If you are greeted by “Welcome to Jenkins!”, everything is fine. If not, then I can’t help you since I was lucky enough to get it right the first time, sorry.</p>
<h2 id="securing-jenkins">Securing Jenkins</h2>
<p>As you may have noted, there was no login or anything, so we need to do some securing so that not everybody can mess with our precious CI setup. Navigate to Manage Jenkins in the left sidebar and then Configure Global Security. Check Enable security, but <strong>do not save yet</strong> (otherwise Jenkins will lock you out). Under Security Realm select your preferred authentication method, I selected “Jenkins’s own user database” and then select the preferred authorization type, I selected “Logged-in users can do anything”. If you also choose to use Jenkins’s own user database, make sure to keep the “Allow users to sign up” checked for now. Then hit save.</p>
<p>Jenkins will now kick you out, so to speak, and present you with a login screen. If you followed my example and chose the same authentication method, you should see “Create an account” link. Follow that and create a new account. After you have successfully created a new account, you are automatically logged in. Then go back to “Configure Global Security” and disable “Allow users to sign up” to prevent anonymous users from creating accounts.</p>
<h2 id="github-integration">GitHub integration</h2>
<p>Next we will integrate Jenkins with GitHub to automatically trigger builds in Jenkins when new code has been pushed to GitHub or new pull requests are opened.</p>
<p>For this we will need to install a few plugins. Go to “Manage Jenkins” and then “Manage Plugins”. Select the Available tab and scroll or filter to find a plugin called “GitHub Plugin” and check it, click “Install without restart”. On the next page you will see the progress of the install, you can check the “Restart Jenkins when installation is complete and no jobs are running” so you will not have to restart it manually.</p>
<p>Next go to “Manage Jenkins” and then “Configure System”. Halfway down the page, you will find Git plugin with a button “Git installations…”. If you have git installed by yum etc. you will not have to change anything here. Otherwise install git and type the install dir here. At the bottom you can find a section called GitHub Web Hook. Select “Let Jenkins auto-manage hook URLs” and add your GitHub username (or create a specific user in GitHub for Jenkins) and API key. After that, hit Save.</p>
<p>Finally we need to configure a Service Hook in GitHub. Go to your projects settings page and click “Service Hooks”. Scroll down until you find “Jenkins (GitHub plugin)” and click it. Add the url of your jenkins server followed by /github-webhook/ (i.e. http://serverAddress:8080/github-webhook/) and Save.</p>
<h2 id="create-a-job-for-the-project">Create a job for the project</h2>
<p>In Jenkins you will need to create a job for something you wish to build periodically. The job represents our project in GitHub that we wish to build. Click “New Job” and fill in a job name (it’s going to be easier if you use only alphanumeric characters because Jenkins will create a folder with this name in the filesystem) and then select free-style software project.</p>
<p>After creating a job, you will be presented with the job configuration view. You will need your GitHub repository URL. Paste the HTTPS URL to the “GitHub project” field at the top and then under “Source Code Management” select Git and paste the SSH URL into the text field. Under “Build Triggers” check “Build when a change is pushed to GitHub” and save.</p>
<p>Now the job has been created but as you might have noticed, Jenkins is still not able to access the repository, at least if it is private. You will need to set up SSH keys in the Jenkins home directory. My setup did not allow me to “su” as user jenkins, so I had to do this as root. I created a new key normally for the root user, saved it to GitHub (I used the per repository “Deploy Keys” option) and then connected to the repository from command line (so that a known_hosts file was created). Then I copied the key files and the known_hosts file to /var/lib/jenkins/.ssh and chown’d them to jenkins:jenkins. After that the job configuration page warning did not appear anymore and everything was working fine. Note. you must pay attention to the file permissions of the files inside .ssh folder (and the folder itself) when moving from somewhere else. If you are not familiar with SSH keys or GitHub “Deploy Keys” feature, here a few helpful links:</p>
<ul>
<li><a href="https://help.github.com/articles/generating-ssh-keys">Generating SSH Keys</a> at GitHub Help</li>
<li><a href="https://developer.github.com/guides/managing-deploy-keys/#deploy-keys">Managing Deploy Keys</a> at GitHub Developer</li>
</ul>
<h2 id="create-a-build-file">Create a build file</h2>
<p>Now that we have a job for our project, we need to have that job do something, e.g. build. Jenkins supports Ant and Maven builds by default, as well as executing bare command line commands. We are going to use Ant, so first we need to install it. I followed the steps outlined in this page to get it installed: <a href="http://xmodulo.com/2013/03/how-to-install-apache-ant-on-centos.html">http://xmodulo.com/2013/03/how-to-install-apache-ant-on-centos.html</a>. After that go to Jenkins configuration “Manage Jenkins” and then “Configure System” and click the “Ant installations…” button in the Ant section. Add a new Ant and give it a name (I named mine “Default”) and point it to the ANT_HOME directory and Save.</p>
<p>Next we need to create a build file for our project. What tasks you want to do in a build really depends on the project, but some obvious choices for a PHP project are things like execute unit tests, analyse code coverage of test, generate API documentation and run static code analysis (like PHP_CodeSniffer, PHP_Depend, PHP Mess Detector, PHP Copy/Paste Detector and PHPLOC). A great resource for PHP related Jenkins setup can be found in <a href="http://jenkins-php.org/">http://jenkins-php.org/</a>. They also have a sample build.xml file that has configuration for all of the above tasks. You can start with that and modify it to your liking and the requirements for your project. The build.xml file should be placed at the root folder of the project, and pushed to GitHub. You can of course play around with it and test different tasks before committing. Also make sure that all the tools you are going to use in the build are installed on the server. A good resource on these is The PHP Quality Assurance Toolchain at <a href="http://phpqatools.org/">http://phpqatools.org/</a></p>
<h2 id="configure-jenkins-to-execute-the-build">Configure Jenkins to execute the build</h2>
<p>After we have a working build.xml committed to GitHub, we need to configure Jenkins to execute the build. Open the “Configure” page under the job created previously. Scroll down to “Build” section and click “Add build step” and select “Invoke Ant”. In the “Targets” input, type the build targets you wish to execute. This really depends on your build file, but in case of the sample build file it should be “build” (or “build-parallel”).</p>
<p>Now when you push new changes to GitHub Jenkins will automatically download the new code and execute the build tasks. Way to go! If you get a blue dot beside the project name in the Jenkins home page, your build was successful. If you get a red dot, you were not so lucky and you got some fixing to do. Either some of your build tasks failed to run at all, or you tests didn’t pass etc. You can check the console output of all the executed tasks by clicking the build and the “Console Output” on the left sidebar. And if you would like to have a green dot on successful builds rather than a blue one, there is a plugin for that.</p>
<h2 id="continuous-inspection-of-code-quality">Continuous Inspection of code quality</h2>
<p>Now that we have Continuous Integration set up, I am going to focus on <a href="http://cvuorinen.net/2013/07/installing-sonarqube-with-jenkins-integration-for-a-php-project/">installing Sonar for running Continuous Inspection of code quality and integrating it with Jenkins</a>.</p>
Sun, 30 Jun 2013 00:00:00 +0000http://cvuorinen.net/2013/06/installing-jenkins-ci-server-with-github-integration-for-a-php-project/
http://cvuorinen.net/2013/06/installing-jenkins-ci-server-with-github-integration-for-a-php-project/Continuous IntegrationPHPTestingProgrammingValidating data with triggers in MySQL<p>MySQL triggers can be used to create some validation conditions that are a little bit more complex than what can be achieved with basic data types and unique index for example. The reason why data validation is better kept at the database level rather than application level is that in case the same data source is used by multiple applications, or even multiple interfaces within the same application, is that you can rely on the data being consistent and valid regardless the validation logic on the application side, which might not always be consistent across different implementations.</p>
<!--more-->
<p>So why triggers are ideal for this kind of logic? Triggers can be executed before data is inserted or updated into the database, and you have the values that would be inserted to the database at your disposal, as well as the old values of the row in case of an update. The insert or update can also be prevented from actually executing from the trigger with an error message. This makes it an ideal place to consistently enforce some validation logic in my opinion.</p>
<p>There are many great tutorials about MySQL triggers, so I will not write about that. If you are not familiar with triggers, I suggest you first read a <a href="http://net.tutsplus.com/tutorials/databases/introduction-to-mysql-triggers/">tutorial</a> or <a href="http://www.sitepoint.com/how-to-create-mysql-triggers/">a few</a>, or check out the <a href="http://dev.mysql.com/doc/refman/5.5/en/triggers.html">MySQL manual</a>.</p>
<h2 id="sql-error-cannot-add-or-update-a-row">SQL Error: Cannot add or update a row</h2>
<p>So we can do the validation in an IF statement inside the trigger, but how can we cancel the insert/update and throw an error? MySQL 5.5 introduced the handy <em><a href="http://dev.mysql.com/doc/refman/5.5/en/signal.html">SIGNAL</a></em> operator that can be used to do just that. It allows to set a specific error condition (or SQLSTATE) and a custom error message. This is exactly what we need in this case, as it will return a native MySQL error and thus also prevent the insert or update clause (as long as we use it in a trigger that is specified to run before insert or update).</p>
<p>But what about MySQL 5.1 (or even 5.0)? If you are still running old versions, the <em>SIGNAL</em> statement will trigger a generic MySQL syntax error about the <em>SIGNAL</em> statement when creating the trigger so you can’t use that. A simple trick is to call a non existing stored procedure to trigger a MySQL error. If you use some generic name for the non existing procedure, like <em>throw_error()</em>, you will not be getting a very useful error message so it can be quite confusing especially for people that do not know about this trigger and the constraint it enforces. This can be improved a little bit by using the error message in the actual call, so the error message becomes a little bit more relevant.</p>
<h2 id="example">Example</h2>
<p>So here is an example of a case where a table has a foreign key to another table and the relationship between them is one-to-many, but the table also has an <em>active</em> boolean field (0|1) and there should always be only one active row per relationship.</p>
<div class="language-sql highlighter-rouge"><pre class="highlight"><code><span class="k">DELIMITER</span> <span class="err">$$</span>
<span class="k">CREATE</span> <span class="k">TRIGGER</span> <span class="n">example_before_insert_allow_only_one_active</span>
<span class="k">BEFORE</span> <span class="k">INSERT</span> <span class="k">ON</span> <span class="n">example_tbl</span> <span class="k">FOR</span> <span class="k">EACH</span> <span class="k">ROW</span>
<span class="k">BEGIN</span>
<span class="n">IF</span> <span class="k">NEW</span><span class="p">.</span><span class="n">active</span> <span class="o">=</span> <span class="mi">1</span> <span class="k">AND</span> <span class="p">(</span><span class="k">SELECT</span> <span class="k">COUNT</span><span class="p">(</span><span class="n">id</span><span class="p">)</span> <span class="k">FROM</span> <span class="n">example_tbl</span>
<span class="k">WHERE</span> <span class="n">active</span><span class="o">=</span><span class="mi">1</span> <span class="k">AND</span> <span class="n">foreign_key_id</span><span class="o">=</span><span class="k">NEW</span><span class="p">.</span><span class="n">foreign_key_id</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span>
<span class="k">THEN</span>
<span class="n">SIGNAL</span> <span class="k">SQLSTATE</span> <span class="s1">'45000'</span>
<span class="k">SET</span> <span class="k">MESSAGE_TEXT</span> <span class="o">=</span> <span class="s1">'Cannot add or update row: only one active row allowed per type'</span><span class="p">;</span>
<span class="k">END</span> <span class="n">IF</span><span class="p">;</span>
<span class="k">END</span><span class="p">;</span>
<span class="err">$$</span>
<span class="k">CREATE</span> <span class="k">TRIGGER</span> <span class="n">example_before_update_allow_only_one_active</span>
<span class="k">BEFORE</span> <span class="k">UPDATE</span> <span class="k">ON</span> <span class="n">example_tbl</span> <span class="k">FOR</span> <span class="k">EACH</span> <span class="k">ROW</span>
<span class="k">BEGIN</span>
<span class="n">IF</span> <span class="k">NEW</span><span class="p">.</span><span class="n">active</span> <span class="o">=</span> <span class="mi">1</span> <span class="k">AND</span> <span class="p">(</span><span class="k">SELECT</span> <span class="k">COUNT</span><span class="p">(</span><span class="n">id</span><span class="p">)</span> <span class="k">FROM</span> <span class="n">example_tbl</span>
<span class="k">WHERE</span> <span class="n">id</span><span class="o">&lt;&gt;</span><span class="k">NEW</span><span class="p">.</span><span class="n">id</span> <span class="k">AND</span> <span class="n">active</span><span class="o">=</span><span class="mi">1</span> <span class="k">AND</span> <span class="n">foreign_key_id</span><span class="o">=</span><span class="k">NEW</span><span class="p">.</span><span class="n">foreign_key_id</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span>
<span class="k">THEN</span>
<span class="n">SIGNAL</span> <span class="k">SQLSTATE</span> <span class="s1">'45000'</span>
<span class="k">SET</span> <span class="k">MESSAGE_TEXT</span> <span class="o">=</span> <span class="s1">'Cannot add or update row: only one active row allowed per type'</span><span class="p">;</span>
<span class="k">END</span> <span class="n">IF</span><span class="p">;</span>
<span class="k">END</span><span class="p">;</span>
<span class="err">$$</span>
</code></pre>
</div>
<p>Here is a sample output from an update statement that does not pass the validation logic:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>mysql&gt; UPDATE example_tbl SET active=1 WHERE id=2;
ERROR 1644 (45000): Cannot add or update row: only one active row allowed per type
</code></pre>
</div>
<p>Here is the same example for older MySQL versions that do not support the <em>SIGNAL</em> statement. Here we are using the same error message, but this time we are trying to call it as a stored procedure. Not that pretty, but it works.</p>
<div class="language-sql highlighter-rouge"><pre class="highlight"><code><span class="k">DELIMITER</span> <span class="err">$$</span>
<span class="k">CREATE</span> <span class="k">TRIGGER</span> <span class="n">example_before_insert_allow_only_one_active</span>
<span class="k">BEFORE</span> <span class="k">INSERT</span> <span class="k">ON</span> <span class="n">example_tbl</span> <span class="k">FOR</span> <span class="k">EACH</span> <span class="k">ROW</span>
<span class="k">BEGIN</span>
<span class="n">IF</span> <span class="k">NEW</span><span class="p">.</span><span class="n">active</span> <span class="o">=</span> <span class="mi">1</span> <span class="k">AND</span> <span class="p">(</span><span class="k">SELECT</span> <span class="k">COUNT</span><span class="p">(</span><span class="n">id</span><span class="p">)</span> <span class="k">FROM</span> <span class="n">example_tbl</span>
<span class="k">WHERE</span> <span class="n">active</span><span class="o">=</span><span class="mi">1</span> <span class="k">AND</span> <span class="n">foreign_key_id</span><span class="o">=</span><span class="k">NEW</span><span class="p">.</span><span class="n">foreign_key_id</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span>
<span class="k">THEN</span>
<span class="k">CALL</span> <span class="nv">`'Cannot add or update row: only one active row allowed per type'`</span><span class="p">;</span>
<span class="k">END</span> <span class="n">IF</span><span class="p">;</span>
<span class="k">END</span><span class="p">;</span>
<span class="err">$$</span>
<span class="k">CREATE</span> <span class="k">TRIGGER</span> <span class="n">example_before_update_allow_only_one_active</span>
<span class="k">BEFORE</span> <span class="k">UPDATE</span> <span class="k">ON</span> <span class="n">example_tbl</span> <span class="k">FOR</span> <span class="k">EACH</span> <span class="k">ROW</span>
<span class="k">BEGIN</span>
<span class="n">IF</span> <span class="k">NEW</span><span class="p">.</span><span class="n">active</span> <span class="o">=</span> <span class="mi">1</span> <span class="k">AND</span> <span class="p">(</span><span class="k">SELECT</span> <span class="k">COUNT</span><span class="p">(</span><span class="n">id</span><span class="p">)</span> <span class="k">FROM</span> <span class="n">example_tbl</span>
<span class="k">WHERE</span> <span class="n">id</span><span class="o">&lt;&gt;</span><span class="k">NEW</span><span class="p">.</span><span class="n">id</span> <span class="k">AND</span> <span class="n">active</span><span class="o">=</span><span class="mi">1</span> <span class="k">AND</span> <span class="n">foreign_key_id</span><span class="o">=</span><span class="k">NEW</span><span class="p">.</span><span class="n">foreign_key_id</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span>
<span class="k">THEN</span>
<span class="k">CALL</span> <span class="nv">`'Cannot add or update row: only one active row allowed per type'`</span><span class="p">;</span>
<span class="k">END</span> <span class="n">IF</span><span class="p">;</span>
<span class="k">END</span><span class="p">;</span>
<span class="err">$$</span>
</code></pre>
</div>
<p>And here is the sample output from an update statement:</p>
<div class="highlighter-rouge"><pre class="highlight"><code>mysql&gt; UPDATE example_tbl SET active=1 WHERE id=2;
ERROR 1305 (42000): PROCEDURE database.'Cannot add or update row: only one active row allowed per type' does not exist
</code></pre>
</div>
<h2 id="conclusion">Conclusion</h2>
<p>Data validation should be consistent across all applications or interfaces using given data source to enforce data integrity and validity. This can be hard to achieve especially if multiple developers use the same data source in different applications. Keeping the validation logic at the data source itself, in this case in a MySQL database, makes sure that the same validation logic is applied always and across all applications and even command line users accessing the database. Triggers are an ideal place to create such validation when basic data type and index rules are not enough.</p>
<p>Of course this does not mean you can forget about data validation in your application, you should always filter or validate user submitted data and give users meaningful error messages.</p>
Tue, 14 May 2013 00:00:00 +0000http://cvuorinen.net/2013/05/validating-data-with-triggers-in-mysql/
http://cvuorinen.net/2013/05/validating-data-with-triggers-in-mysql/MySQLProgramming