Archive

Posts Tagged ‘PHP’

user settings cookie

January 17th, 2010

Sometimes in applications you will have certain user settings that you want to apply, even when the user is not logged in. Take for instance these examples:

  • “welcome back <name>” msg on return.
  • You have a portal type page where the user can control what content is shown where
  • You want to track where the user was when he last visited the site, perhaps to offer him the option to return to there.

I recently needed some functionality like that. So I’ve created a object that can help me with that.

I thought about it for a moment and created a singleton settings object for me to call upon to set and retrieve certain settings. Now I have to warn you that there is a small problem with singletons, if you use unit testing it can be difficult to control the behaviour of singletons over multiple tests. So be wary of this when you are running unit tests.

I also wrap all data in a separate array. This isn’t really necessary, but it makes handling the data a lot easier. If you wanted you could also add some sort of encryption to the cookie data so that users couldn’t easily tamper with it.

PHP, software development , , , ,

Why I think test driven development suck

August 29th, 2009

TDD - All code is guilty until proven innocentWell I figured a provocative title like that would catch your attention, so please read on to find out I am not as stupid as you might think.

Unit tests are great, they reduce unknown bugs and arguably lead to better object design. The reasons for this are simple; Well thought out unit tests will force you to think about the input and output of any method your objects may have, forcing you to correctly decomposition the needed functionality within your object, because methods that have too much responsibility are a pain in the ass to write unit tests for. Simple one task methods however are easy to write unit tests for. Because your writing unit tests you are (hopefully) actively thinking about what can go wrong so that methods can actually fail.

So taking for granted that the above is true, why does test driven development suck?
Well the answer to that is a market one and really only applies to professional business. When a client comes to your business and asks for a offer for his project, you will quote him X, where X is roughly the amount of hours it takes to create the unit tests and then fill in the code + other stuff.

A development house that doesn’t use test driven development will quote that same client only for the time it takes to write the code + other stuff. We all know that after that he will spend a few weeks/months bugfixing, but that’s not what he quotes or tells the client.

Naturally the client will more often then not choose your competitor, unless you can positively convince him that the extra hours you spend will actually save him money in the long run. Which from the clients standpoint is a bit of an unproven claim if he is not technically inclined. So from a business standpoint, test driven development sucks as a selling tool.

Secondly, while this heavily depends on the morality of your business, those bugfix hours can be profitable. Depending on how smooth your talk is, you could very well be billing the client for those hours.

Thirdly, test driven development often suffers when deadlines need to be met. We all know that estimated hours is an imperfect science and often goes wrong, be it overconfident developers or overselling sales people, deadlines tend to be missed in our industry. So when deadlines are creeping, unit tests are often one of the first things to be dropped off schedule. Yes, we all know that shouldn’t happen, but it does. Once this has happened and no extra time is allocated to bring the tests up-to-date again (good luck getting that approved), the test driven development has failed and you’re just plainly developing again.

So for these reasons I think test driven development sucks. I might sometimes use it for private projects or open-source projects (for which I think it is absolutely brilliant), but certainly not for business ones. With the possible exception of in-house developed products, but I haven’t had much experience with that.

For anyone who now still thinks TDD is a sound development methodology, I would be very interested to hear you thoughts.

PHP, software development , , , , , ,

Setting up simple but easy to work with LAMP development environment

August 13th, 2009

I’ve recently changed the way I work so I figured I would detail it here.

First off all let me describe the setup. Basically all my code resides in a subversion repository on server X. My development environment is a virtual server run on virtualbox, a default ubuntu server with a LAMP stack. On my client I run the PDT edition of eclipse with subclips installed.

The client side:

  • Install PDT eclipse, you can download it from http://www.eclipse.org/pdt/downloads/.
  • Go to http://subclipse.tigris.org/ and follow the text to install it into your eclipse installation.
  • In your eclipse choose import from the file menu and select “checkout project from SVN”
  • You now should have a checkout on disk inside a project to work from in eclipse

Development environment side:

  • Create and setup a LAMP based virtual server. (I’m going to assume ubuntu because that’s what I’ve used)
  • Create a virtual host for your project.

The actual interesting bit:

Now the above is really standard stuff, so that’s why it’s a bit brief, but now comes the interesting bit.

What we want to do is mount the code checkout from your client machine as the serving directory of your development environment. Because I’m lazy I want to be able to do this with one click of the button, so we are going to break some security things to be able to do this via the browser.

We want the apache user (www-data in my case) to be able to mount via sshfs and unmount. This will enable it to mount the checkout from my client pc to the serving directory of apache on the virtual server.

First we want to add www-data to the fuse usergroup, we do this via the following command.

sudo usermod -G fuse www-data

Now the www-data user will be allowed to use sshfs.

Next we create the file /var/www/index.php and put some code into it. The following code is really simple and could probably be made more elegant but currently I don’t care :)


<?

if ($_GET['mount']=='myproject' )
  `sshfs user@192.168.1.20:/home/demo/workspace/myproject /var/www/myproject`;

if ($_GET['umount']=='myproject')
  `sudo umount /var/www/myproject/`;

if (is_file('/var/www/myproject/index.php'))
{
?>
myproject is currently mounted -- <a href="?umount=myproject" />umount</a>
<?
}else{
?>
myproject is currently not mounted -- <a href="?mount=myproject" />mount</a>
<?
}

What this allows us to do is to go to the default hosts index.php and remotely tell the server to mount or unmount the environment. There are a few things we need to do to actually make the above code work though.

First the mounting.
sshfs uses ssh, so since we want to use it without user interaction we need to create a private and public key for www-data.


sudo su - www-data
/bin/bash
ssh-keygen

After that you should have a set of keys, then copy the public key to your client and add it in ~/.ssh/authorized_keys of the user you need to log into.

Now the mounting of the repository should work.

However for the unmounting we need to use sudo to get the rights to do that. So for that we need to edit /etc/sudoers on the virtual server and add the following line somewhere.

www-data ALL = NOPASSWD: ALL

Yes, it would be much safer to not allow ALL, but only the umount, but for my virtual development box i’m really not concerned with security, I just want a trouble free and quick fix.

So now I created a simple script that will let me mount and unmount my working copy of the code on the virtual server.

I typed this all up rather quickly so if anyone wants some parts explained in some more detail just leave a comment.

apache2, PHP, software development , , , ,

Intermediate regex use

March 2nd, 2009

Now regexes are a wonderful thing. Personally i can’t get enough of them. they are terse, compact, to-the-point and have a extremely high geek value. Below I will show a example of how you can use simple regular expression rules to accomplish a non-trivial task.

shortening a text

Often we will want to show a short excerpt of a full text, think for instance about articles and what not. A common but ugly way to do this is via substr(). A much more elegant way is via a regular expression.

A easy way to do this is via the following one liner.

preg_replace('/(.{1,250}\.)\s.*/ms','\1', $text );

What this does is select all text, with a sub selection that selects the greatest range of all characters between 1 and 250 ending on a dot. Then it replaces the text with that sub-selection. Resulting in a excerpt that will have the maximum amount of characters up till 250, but will likely end with a full sentence.

There is still the case that no dot is present in the first 250 characters, so you will have to test the output of the preg_replace. But more often then not, the above will work.

Now let’s look at what is happening.

/(.{1,250}

Immediately from the start we open a sub-expression to match the beginning of the text. The dot character gets interpreted as “any possible character except newline”. We then use the brackets to set a quantifier from 1 to 250 characters on the dot character, which means we want to match anything as long as it’s either 1 or 250 characters long.

Since the default behaviour for quantifiers is to be greedy, it will try to match the maximum amount of characters.

\.)\s

Now that we have defined the amount of text we want to match, we are going to define the ending of this match. This, as stated before, is simply a dot. We have to escape that dot as to not match everything. Then we end the sub-expression since this is everything we want.

However it’s not everything we want to test for. So right after the sub-expression I ask to match a whitespace character (\s). This will ensure that it’s actually the ending of a sentence and not for instance the URL of a domain.

.*/ms','\1', $text );

Now that we are done with the desired selection we simply state “.*” Which will match all characters zero or more times.

Then in the replacement section of preg_replace we state that we want to back reference the result of the first sub-expression, and we are done.

As you might have noticed I added a “m” and “s” to the end of my matching expression, these are global modifiers that will change the behaviour of the expression.

The “m” stands for multiline, which will change the default behaviour of starting and stopping at new lines, to match a entire text. The “s” modifies the behaviour of the “.” character to also match newlines. You will often see these two modifiers combined because without the “s” modifier a expression like /.*/m would still only match till the first newline.

Now the above is certainly not watertight, it’s just the illustrate how versatile regular expressions can be and how you can take advantage of the more advanced uses of it.

If you are interested in learning more about regular expressions in PHP I would advise you to go read the PCRE pattern modifiers page and the regexp reference page.

PHP , , , ,

PHP loose typing quiz

February 13th, 2009

Some time ago there was a topic on the daily WTF about a bit of PHP code which was rather funny.

if (!count($items)>0) { something(); }

On first instance this looks rather normal, but it doesn’t exactly do what you think it does. When you read it, you might assume the “!” will invert the expression “count($items)>0″. This however is false, what get’s inverted is “count($items)”.

The reason this is funny, is because it actually does work. We want the full expression to be TRUE when there are zero items in $items. When count($items) is 0, this get’s converted to a boolean for the “!”, which will be FALSE. The “!” kicks in and it get’s flipped to TRUE. Then we are asking if TRUE is larger then 0.  Now TRUE get’s converted to 1, or the right side 0 to FALSE, it doesn’t really matter. The end result is that we are asking if 1>0, which is TRUE.

So to show in code, what happens is something like this.

if (!count($items)>0) { something(); }
if (!0>0) { something(); }
if (!FALSE>0) { something(); }
if (TRUE>0) { something(); }
if (TRUE>FALSE) { something(); }
if (TRUE) { something(); }

Instead of what we might have initially expected

if (!count($items)>0) { something(); }
if (!0>0) { something(); }
if (!FALSE) { something(); }
if (TRUE) { something(); }

It’s always good to keep such things in mind while working in PHP, because seemingly innocent code can have very unexpected side effects. In this case it’s a bit harmless because the end result is the same, but sometimes this may not be the case.

As a good example of a less obvious deathtrap, please answer me the following question.

$items = '';
if (count($items)>0) { something(); }

Does “something();” get executed or not?

PHP , , ,