Planet-PHP
Full Test Coverage is Impractical
Many developers claim that to achieve high quality software, developers must create automated tests that ensure that all possible execution routes have been covered. This is also known as full path coverage. I will argue that different types of software require different testing approaches and that full path coverage is impractical in almost every case. Too many tests simply create clutter.

Let’s look at the impracticality first. Writing tests requires skill and effort. Everybody on your team is probably not a testing expert. Not only may it be difficult to get started with testing, but you will generate a great amount of code with its load of maintenance. Tests are not immune to their own errors either. I have uncovered a number of incorrect test cases in every project, including PHP itself.
A full coverage can give a fake sense of security, because you won’t second guess your tests and there will be too many to effectively audit them. That doesn’t mean that more tests is bad. It means that you must strike a good balance between the number of tests and the assurance that you are seeking. Look at it as a car insurance that costs more per year than the price on your car. You want to feel safe with the right insurance, but at some point, it’s more trouble than it’s worth. You can easily end up with more test code than software code, so watch out.
My second point is that different software justifies different tests. Software that is meant to be used by other software — such as a programming language, a framework or an API — would require more in-depth testing. I would recommend writing a few tests per function, to make sure that they return expected values. Testing all paths may still not be necessary, because some paths may prove redundant. Let’s take a date parsing function as an example. If you can parse “2013-05-22 13:00″ and “May 22, 2013 1:00pm” correctly, then perhaps testing the permutation “2013-05-22 1:00pm” may be unnecessary. Be smart about your tests: choose quality over quantity.
For consumer software, you may not need to test everything. I recommend to skip obvious tests. For example, it is obvious that when you first instanciate this class, getTotal() will return zero.
class ShoppingCart {
protected $total = 0;
function getTotal() {
return $this->total;
}
}
Writing overly obvious test cases is like underlining text that is already highlighted. I usually start testing areas that can have impact the business, such as losing data or selling 0.01 quantity of a product.
In the end, there are no exact rules on how much to test. The most important thing to keep in mind is that writing tests for the sake writing tests is futile and costly. Not only that, but your colleagues won’t bother reading or maintaining tests if they are only there for their own sake and provide too little value. Focus on building great software. Tests are a tool to make it better. Just don’t overdo it.
Full Test Coverage is Impractical
Many developers claim that to achieve high quality software, developers must create automated tests that ensure that all possible execution routes have been covered. This is also known as full path coverage. I will argue that different types of software require different testing approaches and that full path coverage is impractical in almost every case. Too many tests simply create clutter.

Let’s look at the impracticality first. Writing tests requires skill and effort. Everybody on your team is probably not a testing expert. Not only may it be difficult to get started with testing, but you will generate a great amount of code with its load of maintenance. Tests are not immune to their own errors either. I have uncovered a number of incorrect test cases in every project, including PHP itself.
A full coverage can give a fake sense of security, because you won’t second guess your tests and there will be too many to effectively audit them. That doesn’t mean that more tests is bad. It means that you must strike a good balance between the number of tests and the assurance that you are seeking. Look at it as a car insurance that costs more per year than the price on your car. You want to feel safe with the right insurance, but at some point, it’s more trouble than it’s worth. You can easily end up with more test code than software code, so watch out.
My second point is that different software justifies different tests. Software that is meant to be used by other software — such as a programming language, a framework or an API — would require more in-depth testing. I would recommend writing a few tests per function, to make sure that they return expected values. Testing all paths may still not be necessary, because some paths may prove redundant. Let’s take a date parsing function as an example. If you can parse “2013-05-22 13:00″ and “May 22, 2013 1:00pm” correctly, then perhaps testing the permutation “2013-05-22 1:00pm” may be unnecessary. Be smart about your tests: choose quality over quantity.
For consumer software, you may not need to test everything. I recommend to skip obvious tests. For example, it is obvious that when you first instanciate this class, getTotal() will return zero.
class ShoppingCart {
protected $total = 0;
function getTotal() {
return $this->total;
}
}
Writing overly obvious test cases is like underlining text that is already highlighted. I usually start testing areas that can have impact the business, such as losing data or selling 0.01 quantity of a product.
In the end, there are no exact rules on how much to test. The most important thing to keep in mind is that writing tests for the sake writing tests is futile and costly. Not only that, but your colleagues won’t bother reading or maintaining tests if they are only there for their own sake and provide too little value. Focus on building great software. Tests are a tool to make it better. Just don’t overdo it.
Full Test Coverage is Impractical
Many developers claim that to achieve high quality software, developers must create automated tests that ensure that all possible execution routes have been covered. This is also known as full path coverage. I will argue that different types of software require different testing approaches and that full path coverage is impractical in almost every case. Too many tests simply create clutter.

Let’s look at the impracticality first. Writing tests requires skill and effort. Everybody on your team is probably not a testing expert. Not only may it be difficult to get started with testing, but you will generate a great amount of code with its load of maintenance. Tests are not immune to their own errors either. I have uncovered a number of incorrect test cases in every project, including PHP itself.
A full coverage can give a fake sense of security, because you won’t second guess your tests and there will be too many to effectively audit them. That doesn’t mean that more tests is bad. It means that you must strike a good balance between the number of tests and the assurance that you are seeking. Look at it as a car insurance that costs more per year than the price on your car. You want to feel safe with the right insurance, but at some point, it’s more trouble than it’s worth. You can easily end up with more test code than software code, so watch out.
My second point is that different software justifies different tests. Software that is meant to be used by other software — such as a programming language, a framework or an API — would require more in-depth testing. I would recommend writing a few tests per function, to make sure that they return expected values. Testing all paths may still not be necessary, because some paths may prove redundant. Let’s take a date parsing function as an example. If you can parse “2013-05-22 13:00″ and “May 22, 2013 1:00pm” correctly, then perhaps testing the permutation “2013-05-22 1:00pm” may be unnecessary. Be smart about your tests: choose quality over quantity.
For consumer software, you may not need to test everything. I recommend to skip obvious tests. For example, it is obvious that when you first instanciate this class, getTotal() will return zero.
class ShoppingCart {
protected $total = 0;
function getTotal() {
return $this->total;
}
}
Writing overly obvious test cases is like underlining text that is already highlighted. I usually start testing areas that can have impact the business, such as losing data or selling 0.01 quantity of a product.
In the end, there are no exact rules on how much to test. The most important thing to keep in mind is that writing tests for the sake writing tests is futile and costly. Not only that, but your colleagues won’t bother reading or maintaining tests if they are only there for their own sake and provide too little value. Focus on building great software. Tests are a tool to make it better. Just don’t overdo it.
Simplest PHP Generator Example
I really like the generators feature that's arriving in PHP 5.5, and since we're now into release candidate releases, it's actually not that far away. I've been speaking on this topic and I thought I'd share my trivially simple code example from my slides.
Writing a GeneratorThe generators use the yield keyword to feed values out as they are iterated over. In code, they really look a lot like a function (or method):
<?php function getValues() { // totally trivial example yield "Apple"; yield "Ball"; yield "Cat"; }
The main difference is that this "function" will retain its state and yield the next value when it is used again.
Using a GeneratorIt's not obvious from the calling code that a generator is in use - and that's a feature IMO. Here's an example that uses the generator declared above:
<?php $stuff = getValues(); foreach($stuff as $thing) { echo $thing . "\n"; }
From this, you might assume that
getValues() returns an iterator or array. I can imagine refactoring applications that absolutely do expect either of those to use generators instead, so that's intentional! If you do var_dump($stuff), however, you'll see an object of type Generator.
Each time the foreach tries to fetch the next item from $stuff, the getValues() generator gets called, and runs until a yield statement causes a value to be emitted.
There's nothing in these examples that makes a generator a better choice than, say, returning an array, so why are generators even useful? For the most part, they will be great for either formulaic or very large datasets. If you wanted to perform some task on all prime numbers up to ten digits long, you could certainly generate a list and iterate over it. However, that list could be quite large, and the generator could calculate and supply the next value on an as-needed basis.
The other use is for data sets which are large in comparison to the size of the memory available to PHP. A generator could fetch data in a loop, or read incrementally from a stream, and only have that one piece of data hanging around in PHP's memory at any one time.
Looking Forward to GeneratorsGenerators are just one more in a long string of understated features coming in to the newer versions of PHP, but it's one that will make your data-heavy applications run light and quick - I can't thank the PHP core team enough for bringing us this feature!
Lorna is an independent web development consultant, author and trainer, available for work (interesting projects only). This post was originally published at LornaJane
Simplest PHP Generator Example
I really like the generators feature that's arriving in PHP 5.5, and since we're now into release candidate releases, it's actually not that far away. I've been speaking on this topic and I thought I'd share my trivially simple code example from my slides.
Writing a GeneratorThe generators use the yield keyword to feed values out as they are iterated over. In code, they really look a lot like a function (or method):
<?php function getValues() { // totally trivial example yield "Apple"; yield "Ball"; yield "Cat"; }
The main difference is that this "function" will retain its state and yield the next value when it is used again.
Using a GeneratorIt's not obvious from the calling code that a generator is in use - and that's a feature IMO. Here's an example that uses the generator declared above:
<?php $stuff = getValues(); foreach($stuff as $thing) { echo $thing . "\n"; }
From this, you might assume that
getValues() returns an iterator or array. I can imagine refactoring applications that absolutely do expect either of those to use generators instead, so that's intentional! If you do var_dump($stuff), however, you'll see an object of type Generator.
Each time the foreach tries to fetch the next item from $stuff, the getValues() generator gets called, and runs until a yield statement causes a value to be emitted.
There's nothing in these examples that makes a generator a better choice than, say, returning an array, so why are generators even useful? For the most part, they will be great for either formulaic or very large datasets. If you wanted to perform some task on all prime numbers up to ten digits long, you could certainly generate a list and iterate over it. However, that list could be quite large, and the generator could calculate and supply the next value on an as-needed basis.
The other use is for data sets which are large in comparison to the size of the memory available to PHP. A generator could fetch data in a loop, or read incrementally from a stream, and only have that one piece of data hanging around in PHP's memory at any one time.
Looking Forward to GeneratorsGenerators are just one more in a long string of understated features coming in to the newer versions of PHP, but it's one that will make your data-heavy applications run light and quick - I can't thank the PHP core team enough for bringing us this feature!
Lorna is an independent web development consultant, author and trainer, available for work (interesting projects only). This post was originally published at LornaJane
Simplest PHP Generator Example
I really like the generators feature that's arriving in PHP 5.5, and since we're now into release candidate releases, it's actually not that far away. I've been speaking on this topic and I thought I'd share my trivially simple code example from my slides.
Writing a GeneratorThe generators use the yield keyword to feed values out as they are iterated over. In code, they really look a lot like a function (or method):
<?php function getValues() { // totally trivial example yield "Apple"; yield "Ball"; yield "Cat"; }
The main difference is that this "function" will retain its state and yield the next value when it is used again.
Using a GeneratorIt's not obvious from the calling code that a generator is in use - and that's a feature IMO. Here's an example that uses the generator declared above:
<?php $stuff = getValues(); foreach($stuff as $thing) { echo $thing . "\n"; }
From this, you might assume that
getValues() returns an iterator or array. I can imagine refactoring applications that absolutely do expect either of those to use generators instead, so that's intentional! If you do var_dump($stuff), however, you'll see an object of type Generator.
Each time the foreach tries to fetch the next item from $stuff, the getValues() generator gets called, and runs until a yield statement causes a value to be emitted.
There's nothing in these examples that makes a generator a better choice than, say, returning an array, so why are generators even useful? For the most part, they will be great for either formulaic or very large datasets. If you wanted to perform some task on all prime numbers up to ten digits long, you could certainly generate a list and iterate over it. However, that list could be quite large, and the generator could calculate and supply the next value on an as-needed basis.
The other use is for data sets which are large in comparison to the size of the memory available to PHP. A generator could fetch data in a loop, or read incrementally from a stream, and only have that one piece of data hanging around in PHP's memory at any one time.
Looking Forward to GeneratorsGenerators are just one more in a long string of understated features coming in to the newer versions of PHP, but it's one that will make your data-heavy applications run light and quick - I can't thank the PHP core team enough for bringing us this feature!
Lorna is an independent web development consultant, author and trainer, available for work (interesting projects only). This post was originally published at LornaJane
Code complexity and clean code
Code complexity and clean code
Code complexity and clean code
Development By The Numbers - Slides
Dear Ed (A response to Open Sourcing Mental Illness at php[tek] 2013)
Note: this post is personal, and may contain triggers for those suffering through grief. Due to it’s nature, I did pass it by Ed before posting it publicly, as every body is different when dealing with their mental illnesses, and this is such a complex topic that it’s difficult to talk about without drawing broad brush strokes that may offend some people. Please keep in mind that this is [some of] my thoughts on this very complicated subject, and you are free to disagree.
Dear Ed,
I felt that I needed to write this letter to you, and I wanted it to be open because I think it’s an appropriate way to participate in open sourcing mental illness. Consider this a pull request of sorts. The only way to remove the stigma around this topic is by talking frankly and openly about it.
I’m writing this (specifically) in response to the talk you gave at php[tek] last week. I remember first meeting you, at php|tek (as it was then known) in Chicago, sometime around 2003-4, one of my first conferences. You had some local friends meeting you there and we all hung out at the hotel bar. It was fun. But I remember the intimidation of meeting this hard core rock looking dude that I didn’t think I could possibly fit in with and relate to.
I was expecting to find a rough biker type dude, that would beat me up if I said the wrong thing… And I remember you were very intense (which I now know was passion) and I remember the change that came over your entire demeanor when you started talking about your son… The warmth and joy that I saw made me think “holy crap, this guy is just an awesome dad. I like this guy!”. Someone else has described this phenomenon as you turning into a pile of goo. As a fairly new father myself I now understand that so much better — thanks for being one of my first peer role models for being a father.
I don’t suffer from the kinds of mental illness you (we?) are trying to help, I have some very irrational (but “normal”) fears – needles and bugs, especially wasps and spiders – and travel stresses me out (TripIt Pro is so fantastic for helping me with that, ask me if you want details
.
I do however have experience with depression, and related things. I lost my father at age 11, and I lost my (first) wife at 22. These were traumatic, depressive, insane things to go through.
But I did get through them, and I feel stronger and happier at this end of that path. Thanks to folks like Ligaya Turmelle, Joey Smith, Matthew Turland and all three Elizabeths (Smith, Naramore and Tucker-Long), who have all at one time or another been a shoulder for me, I am now in a place where I can be laid back about most issues that many people simply can’t (the things that stress you out and cause anxiety on a daily basis). I live by “It is what it is”. But most folks can’t do that.
It is very difficult for me to relate to what people suffering from mental illness have been through in a lot of ways. The kinds of things I suffered from are considered “normal”, a part of the grieving process, and a temporary state; I personally don’t see it as the same thing as clinical depression — though they can lead to it — but “in the moment” they possibly are very similar.
I do however live with mental illness every day. My wife is bipolar (diagnosed and treated for about 6 years) and suffers from depression and anxieties. I see how it affects her, even with medication, and I really appreciate some more insight into a lot of things that she (like most people) has trouble verbalizing, so that I can help her handle it.
I don’t think I can help people suffering directly, I have no direct experience to draw from, other than my experiences with grief over a lost loved one… but I’m very open to any question about what I went through, and how I dealt with it from anyone (consider that an open invitation to anyone reading this.) But I wanted to let you know you have my support, admiration, and maybe even a little bit of love (OK a lot: internet hugs!) for opening yourself up to help this community we both hold so near and dear.
So, thank you!
- Davey
Survived php tek 2013
If you were last week in Chicago, you've might felt the city was buzzing PHP all over the place. php[tek] 2013 was taking place at the Sheraton Gateway Suites Chicago O'Hare in Rosemont, just outside of Chicago city.This year it was also the first time Musketeers.me, a php consulting team from the East Coast, was running the show, putting their own signature onto the event. And with great success I might add. A well deserved applause to Eli White, Kevin Bruce, Sandy Smith, Oscar Merida and of course the Beth Tucker Long for their unlocked achievement running a great conference.
For me was also the first time I was running the uncon, where attendees and conference speakers could propose talks they wanted to present at the uncon and have other attendees vote for them.
One uncon talk really stood out: "Open Sourcing mental illness" by Ed Finkler (@funkatron) where he discussed the issues people face who suffer a mental illness. It was an emotional talk where Ed described his own experiences and how his mind made him think about things differently then the rest of us. For me it was a real eye-opener and made me understand that there are people that don't really take things for granted.
This year's edition was filed with very good talks and it's almost impossible to give my feedback on all of them. A few talks that I attended really stood out that I would really want to promote here.
Chris Cornut, the driving force behind phpdeveloper.org, talked about "Beyond the Basics: Security with PHP" where he did not just list the top 10 of OWASP, but also gave good advices on how to protect yourself against most of the common attacks. A good closing hint: be better secured than the next guy.
Jeremy Kendall was giving good advice on how to improve your code you wrote a couple of weeks or months ago in his talk "PHP 102: Out with the Bad, In with the Good". What I like about Jeremy is he can bring very complex subjects in an easy, understandable way that even a novice can understand complex software engineering stuff. And so he did with this talk.
One talk I missed which I really wanted to see was the Distractions talk of Sean Prunka, or how to deal with distractions when you're a developer. When I look at the reviews on joind.in I see he did an amazing good job giving this was his first conference talk ever. So hopefully he will do a webinar or an online recording of this talk *hint, hint*.
This year my company was sponsoring the hackathon and can be called a good success, knowing we had to compete against Lego fun party. According to Lorna a bunch of pull requests were made for joind.in (the community feedback platform for conference speakers). And we captured the first pull request on twitter.
Can I get a woot? First @joindin pull request of the night has been merged at #tek13 hackathon!
— Lorna Mitchell (@lornajane) May 16, 2013<script async="" charset="utf-8" src="//platform.twitter.com/widgets.js"/>
At the introduction of the hackathon we also had a nice surprise for Mr. Keith Casey from his colleagues at Twillio where he worked 2 years now.
"/>
Truncated by Planet PHP, read more at the original (another 2560 bytes)
5 Reasons Why the Web Platform War is Over: PHP Won with 75% says Google
Read this article to understand why this puts an end to years of false claims that PHP was losing market, as well what it means to Web developers using PHP or other languages.
Offline Processing in PHP with Advanced Queuing
Offloading slow batch tasks to an external process is a common method of improving website responsiveness. One great way to initiate such background tasks in PHP is to use Oracle Streams Advanced Queuing in a producer-consumer message passing fashion. Oracle AQ is highly configurable. Messages can queued by multiple producers. Different consumers can filter messages. From PHP, the PL/SQL interface to AQ is used. There are also Java, C and HTTPS interfaces, allowing wide architectural freedom.
The following example simulates an application user registration system where the PHP application queues each new user's street address. An external system monitoring the queue can then fetch and process that address. In real life the external system might initiate a snail-mail welcome letter, or do further, slower automated validation on the address.
The following SQL*Plus script qcreate.sql creates a new Oracle user demoqueue with permission to create and use queues. A payload type for the address is created and a queue is set up for this payload.
-- qcreate.sql connect / as sysdba drop user demoqueue cascade; create user demoqueue identified by welcome; grant connect, resource to demoqueue; grant aq_administrator_role, aq_user_role to demoqueue; grant execute on dbms_aq to demoqueue; grant create type to demoqueue; connect demoqueue/welcome@localhost/orcl -- The data we want to queue create or replace type user_address_type as object ( name varchar2(10), address varchar2(50) ); / -- Create and start the queue begin dbms_aqadm.create_queue_table( queue_table => 'demoqueue.addr_queue_tab', queue_payload_type => 'demoqueue.user_address_type'); end; / begin dbms_aqadm.create_queue( queue_name => 'demoqueue.addr_queue', queue_table => 'demoqueue.addr_queue_tab'); end; / begin dbms_aqadm.start_queue( queue_name => 'demoqueue.addr_queue', enqueue => true); end; /
The script qhelper.sql creates two useful helper functions to enqueue and dequeue messages:
-- qhelper.sql
-- Helpful address enqueue/dequeue procedures
connect demoqueue/welcome@localhost/orcl
-- Put an address in the queue
create or replace procedure my_enq(name_p in varchar2, address_p in varchar2) as
user_address user_address_type;
enqueue_options dbms_aq.enqueue_options_t;
message_properties dbms_aq.message_properties_t;
enq_id raw(16);
begin
user_address := user_address_type(name_p, address_p);
dbms_aq.enqueue(queue_name => 'demoqueue.addr_queue',
enqueue_options => enqueue_options,
message_properties => message_properties,
payload => user_address,
msgid => enq_id);
commit;
end;
/
show errors
-- Get an address from the queue
create or replace procedure my_deq(name_p out varchar2, address_p out varchar2) as
dequeue_options dbms_aq.dequeue_options_t;
message_properties dbms_aq.message_properties_t;
user_address user_address_type;
enq_id raw(16);
begin
dbms_aq.dequeue(queue_name => 'demoqueue.addr_queue',
dequeue_options => dequeue_options,
message_properties => message_properties,
payload => user_address,
msgid => enq_id);
name_p := user_address.name;
address_p := user_address.address;
commit;
end;
/
show errors
The script newuser.php is the part of the PHP application that handles site registration for a new user. It queues a message containing their address and continues executing:
<?php
// newuser.php
$c = oci_connect("demoqueue", "welcome", "localhost/orcl");
// The new user details
$username = 'Fred';
$address = '500 Oracle Parkway';
// Enqueue the address for later offline handling
$s = oci_parse($c, "begin my_enq(:username, :address); end;");
oci_bind_by_name($s, ":username", $username, 10);
oci_bind_by_name($s, ":address", $address, 50);
$r = oci_execute($s);
// Continue executing
echo "Welcome $username\n";
?>
It executes an anonymous PL/SQL block to create and enqueue the address message. The immediate script output is simply the echoed welcome message:
Welcome Fred
Once this PHP script is executed, any application can dequeue the new message at its leisure. For example, the following SQL*Plus commands call the helper my_deq() dequeue function and displays the user details:
-- getuser.sql
connect demoqueue/welcome@localhost/orcl
set serveroutput on
declare
name varchar2(10);
address varchar2(50);
begin
my_deq(name, address);
dbms_output.put_line('Name : ' || name);
dbms_output.put_line('Address : ' || address);
end;
/
The
Truncated by Planet PHP, read more at the original (another 1511 bytes)
Slides: Behat & Beautiful APIs
Publishing Security Disclosures In Consumable Formats For Simpler Aggregation and Security Checking
This is a branch off from a separate discussion on the PHP-FIG mailing list about other ways the Framework Interoperability Group can encourage and foster wider interoperability among its member projects (and by extension, the whole PHP community). I’ll start by noting two interesting developments in recent months and one long standing best practice.
1. Launch of the SensioLabs Security Advisory CheckerThe SensioLabs Security Advisor Checker is described on its website as follows.
You manage your PHP project dependencies with Composer, right? But are you sure that your project does not depend on a package with known security issues? The SensioLabs security advisories checker is a simple tool, available as a web service or as an online application, that uses the information from your composer.lock file to check for known security vulnerabilities. This checker is a frontend for the security advisories database.
The service operates by having people submit vulnerability data, as YAML files, to a centralised Github repository through pull requests. The upside is that the vulnerability data can be peer reviewed and centrally dispersed either online or via a service API. The downside is that you need to find vulnerability disclosures and people to submit them. The service currently covers Symfony, Zend Framework, Doctrine, Twig and FriendsOfSymfony bundles. It’s a tiny sample of packages available through Composer. I’m also not entirely sure if it’s sufficiently fine grained to report vulnerabilities on a project’s sub-packages where you have no direct dependency on the aggregate package (e.g. using zendframework/zend-db instead of zendframework/zendframework). That said, this is a working model of a service for checking your dependencies.
That said, the service exhibits an ambitious idea – projects sharing their vulnerability disclosures or advisories in a way that allows for automatically checking if any of your projects need to have their dependencies updated for security reasons.
2. OWASP‘s Top 10 security risks for 2013 includes “A9 – Using Components with Known Vulnerabilities”This is a new entry onto OWASP’s Top 10 (which is currently at release candidate status for 2013). In summary, it recognises that applications are becoming ever more dependent on code not developed internally. We’ve had web application frameworks for years. Composer and Github have unleashed a storm of accessible libraries, bundles, modules, and other units of reuse that have revealed Not Invented Here (NIH Syndrome) as a psychological problem in ways not previously possible.
As reliance on externally controlled dependencies increases, so too does the risk of your applications using insecure dependencies. This is a risk that requires a lot of work to mitigate. For each dependency, you need to do a security review (no, I’m not kidding), check for security disclosures (whether voluntary or involuntary) and ensure that you end up rolling out to production with safe versions.
Quoting from the OWASP advice on preventing the use of components with known vulnerabilities…
One option is not to use compone
Truncated by Planet PHP, read more at the original (another 4681 bytes)
How we organize our websites
We recently migrated Where’s it Up to our fancy new hardware, it took a bit more effort than planned (some pains surrounding our use of MongoDB) but I’m incredibly happy with how things have ended up. As mentioned earlier we’ve purchased our own hardware, and have racked it with Peer 1 here in Toronto. We’ve installed a hypervisor, and are running different VMs for critical services: MySQL, Mongo, Web Production, Web Development, etc.
Our websites sit under /var/www, so Where’s it Up resides at /var/www/wheresitup.com/. Under that directory we have /noweb/apache/ which contains both wheresitup.com and dev.wheresitup.com, configuration files for apache. The entire /var/www/wheresitup.com directory tree resides nicely in our version control system. We hand off key configuration options to our websites through the use of Apache’s SetEnv, things like SetEnv mysql_host dev.mysql, these apache configuration options represent the only difference between the two code bases.
I’ve written or maintained code that implied the state (Dev/Production/Stage) based on the Host, directory, or other factors in the past. I much prefer grabbing an explicit constant. It feels cleaner, I don’t have to read up on which variables could have been manipulated by an attacker, and I can ask the exact question I want answered: Is this dev, rather than “is the url the one that means this is dev”.
This allows us to match our Development and Production virtual machines very closely, the only difference between the two is which apache configuration file is sym-linked under /etc/apache2/conf/sites-enabled. Clearly WebDev links to the dev.wheresitup.com file, and WebProd links to wheresitup.com. We actually cloned one machine to produce the other.
Keeping the configuration files so close also makes a lot of sense to me. If I’m adding a new constant on Dev, the immediate presence of Prod reminds me that I’ll need to add it there as well. Storing the entire site: PHP code, supporting apache configuration, etc, all in once place makes it easy to avoid forgetting anything (which is easy when it's a different file on a different server). The only exception is SSL certificates. We currently host a number of our projects with GitHub, and trust them as we might, we’re not willing to hand those to anyone else.
Dealing with duplicated code
Getting Started with PHP Zend Framework 2 for Oracle DB
This post shows the changes to the ZF2 tutorial application to allow it to run with Oracle Database 11gR2.
Oracle Database SQL identifiers are case insensitive by default so "select Abc from Xyz" is the same as "select abc from xyz". However the identifier metadata returned to programs like PHP is standardized to uppercase by default. After executing either query PHP knows that column "ABC" was selected from table "XYZ".
In PHP code, array indices and object attributes need to match the schema identifier case that is returned by the database. This is either done by using uppercase indices and attributes in the PHP code, or by forcing the SQL schema to case-sensitively use lower-case names.
The former approach is more common, and is shown here.
The instructions for creating the sample ZF2 application are here. Follow those steps as written, making the substitutions shown below.
SchemaIn Oracle 11gR2, the schema can be created like:
DROP USER ZF2 CASCADE;
CREATE USER ZF2 IDENTIFIED BY WELCOME
DEFAULT TABLESPACE USERS QUOTA UNLIMITED ON USERS
TEMPORARY TABLESPACE TEMP;
GRANT CREATE SESSION
, CREATE TABLE
, CREATE PROCEDURE
, CREATE SEQUENCE
, CREATE TRIGGER
, CREATE VIEW
, CREATE SYNONYM
, ALTER SESSION
TO ZF2;
CONNECT ZF2/WELCOME
CREATE TABLE ALBUM (
ID NUMBER NOT NULL,
ARTIST VARCHAR2(100) NOT NULL,
TITLE VARCHAR2(100) NOT NULL,
PRIMARY KEY (ID)
);
CREATE SEQUENCE ALBUMSEQ;
CREATE TRIGGER ALBUMTRIGGER BEFORE INSERT ON ALBUM FOR EACH ROW
BEGIN
:NEW.ID := ALBUMSEQ.NEXTVAL;
END;
/
INSERT INTO ALBUM (ARTIST, TITLE)
VALUES ('The Military Wives', 'In My Dreams');
INSERT INTO ALBUM (ARTIST, TITLE)
VALUES ('Adele', '21');
INSERT INTO ALBUM (ARTIST, TITLE)
VALUES ('Bruce Springsteen', 'Wrecking Ball (Deluxe)');
INSERT INTO ALBUM (ARTIST, TITLE)
VALUES ('Lana Del Rey', 'Born To Die');
INSERT INTO ALBUM (ARTIST, TITLE)
VALUES ('Gotye', 'Making Mirrors');
COMMIT;
Driver and Credentials
The driver and credentials are Oracle-specific. Always use the OCI8 adapter in ZF, since it is more stable and has better scalability. Specifying a character set will make connection faster.
zf2-tutorial/config/autoload/global.php: return array(
'db' => array(
- 'driver' => 'Pdo',
- 'dsn' => 'mysql:dbname=zf2tutorial;host=localhost',
- 'driver_options' => array(
- PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
- ),
+ 'driver' => 'OCI8',
+ 'connection_string' => 'localhost/orcl',
+ 'character_set' => 'AL32UTF8',
),
'service_manager' => array(
'factories' => array(
zf2-tutorial/config/autoload/local.php:
return array(
'db' => array(
- 'username' => 'YOUR USERNAME HERE',
- 'password' => 'YOUR USERNAME HERE',
+ 'username' => 'ZF2',
+ 'password' => 'WELCOME',
),
// Whether or not to enable a configuration cache.
// If enabled, the merged configuration will be cached and used in
Attribute & Index Changes
The rest of the application changes are just to handle the case of the Oracle identifiers correctly.
zf2-tutorial/module/Album/Module.php
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Album());
- return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
+ return new TableGateway('ALBUM', $dbAdapter, null, $resultSetPrototype);
},
),
);
zf2-tutorial/module/Album/view/album/album/add.phtml
$form->prepare();
echo $this->form()->openTag($form);
-echo $this->formHidden($form->get('id'));
-echo $this->formRow($form->get('title'));
-echo $this->formRow($form->get('artist'));
+echo $this->formHidden($form->get('ID'));
+echo $this->formRow($form->get('TITLE'));
+echo $this->formRow($form->get('ARTIST'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
zf2-tutorial/module/Album/view/album/album/delete.phtml
<h1><?php echo $this->escapeHtml($title); ?></h1> <p>Are you sure that you want to delete -'<?php echo $this->escapeHtml($album->title); ?>' by -'<?php echo $this->escapeHtml($album->artist); ?>'? +'<?php echo $this->escapeHtml($album->TITLE); ?>' by +'<?php echo $this->esc
Truncated by Planet PHP, read more at the original (another 7231 bytes)
