Blog

Jean-Michel Feurprier » tips and tricks http://blog.jmfeurprier.com LAMP Web Developer Sat, 13 Feb 2010 00:16:49 +0000 http://wordpress.org/?v=2.9.1 en hourly 1 SVN trunk, branches and tags http://blog.jmfeurprier.com/2010/02/08/svn-trunk-branches-and-tags/ http://blog.jmfeurprier.com/2010/02/08/svn-trunk-branches-and-tags/#comments Tue, 09 Feb 2010 00:27:20 +0000 Jean-Michel Feurprier http://blog.jmfeurprier.com/?p=258 In this post, I provide details about how I personnaly handle SVN trunk, branches and tags. This approach is also known as “branch always”, with minor differences. This might not be the best approach, but it will give beginners some explanations on what trunk, branches and tags are, and how to handle them.

Of course, feel free to leave comments on this post if some clarifications are needed, if some mistakes were made, or if you disagree with my statements.

An easy comparison

Working with SVN is somewhat like growing a tree:

  • a tree has a trunk and some branches
  • branches grow from the trunk, and thinner branches grow from thicker branches
  • a tree can grow with a trunk and no branch (but not for long)
  • a tree with branches but no trunk looks more like a bundle of twigs fallen on the floor
  • if the trunk is sick, so are the branches and eventually, the whole tree can die
  • if a branch is sick, you can cut it, and another one may grow
  • if a branch grows too much, it may become too heavy for the trunk, and the tree will fall down
  • when you feel your tree, your trunk, or a branch is nice looking, you can take a picture of it to remember how nice it was that day

Trunk

With the “branch always” approach, the trunk is the main place were stable code can be found. This is like the assembly line of a car factory, putting finished car parts together.

Here is how you should deal with a SVN trunk:

  • do NEVER work directly on the trunk, unless you have to deal with a bug which is quick and easy to fix (a few characters), or if you have to ADD a few files which hold no logic (like media files: images, videos, css, etc)
  • do not make too many exceptions to the previous statement, those are really special cases, every other situation must imply the creation of a branch (see below)
  • do not commit changes (from a branch merge) to the trunk which may break it
  • if at some point you happen to break the trunk, bring some cake the next day (“with great power comes… huge cake”)

Branches

A branch is a “cheap copy” of a subtree (ie, the trunk or a branch) of a SVN repository. It works a little bit like symbolic links on UNIX systems, except that once you make modifications to files within a SVN branch, these files evolve independently from the original files which were “copied”. When a branch is completed and considered stable, it must be merged back to its original copy, that is: back to the trunk if it was copied from the trunk, or back to its parent branch if it was copied from a branch.

Here is how you should deal with SVN branches:

  • if you need to alter your application or develop a new feature for it, create a new branch from the trunk, and make your development on that branch
  • new branches must be created from the trunk, except for new sub-branches (if needed) which must be created from a branch
  • when you create a new branch, you should switch to it immediately; if you don’t, why did you create the branch in the first place?

Tags

Internally, SVN branches and SVN tags are the same thing, but conceptually, they differ a lot.
Remember the “take a picture of the tree” thing written earlier? Well, this is exactly what a SVN tag is: a snapshot with a name of a specific revision of the trunk, or of a branch.

Here is how you should deal with SVN tags:

  • as a developer, do never switch to/checkout from/commit to a SVN tag: a tag is some sort of “picture”, not the real thing; tags are to be read, never written
  • on specific/critical environments (production, staging, testing, etc), checkout and update from a fixed tag, but do never commit to a tag
  • for the aforementioned environments, create tags with names like “production”, “staging”, “testing”, etc. You can also tag by sofware version and/or by project maturity: “1.0.3″, “stable”, “latest”, etc.
  • when the trunk is stable and ready to be released publicly, re-create tags accordingly, then update the concerned environments (production, staging, etc)
  • do not tag a tag

Example workflow

Say you have to add a feature to a project under version control. Here are the steps you should achieve to do so:

  • get a new working copy of the project (through a SVN checkout or a SVN switch) from the trunk
  • create a new SVN branch and give it a name which allows to understand what it is all about (say, “feature-faq-development”)
  • SVN switch to the new branch (“/branches/feature-faq-development”)
  • make the needed development to complete the new feature (and of course, make a lot of tests, even before you start coding), commit sub-parts of your development when needed
  • once the feature is complete and stable (and committed), merge the trunk into the branch and resolve conflicts if there are some, then commit your changes
  • with the approval of your peers, switch to the trunk
  • merge your branch within your working copy (trunk), and resolve conflicts if there are some
  • re-check your development with the merged code
  • if possible, ask one of your peer to do a code review of your changes with you
  • commit your merged working copy to the trunk
  • if some deployment must be achieved on specific environments (production, etc), update the related tag to the revision you just committed in the trunk
  • deploy on the concerned environments with a SVN update
  • rename the branch so that it’s made clear it won’t be used anymore (“/branches/obsolete-feature-faq-development”)
  • eventually, delete the branch after a while

Extra resources:

]]>
http://blog.jmfeurprier.com/2010/02/08/svn-trunk-branches-and-tags/feed/ 25
method_exists() vs. is_callable() http://blog.jmfeurprier.com/2010/01/03/method_exists-vs-is_callable/ http://blog.jmfeurprier.com/2010/01/03/method_exists-vs-is_callable/#comments Sun, 03 Jan 2010 07:17:24 +0000 Jean-Michel Feurprier http://blog.jmfeurprier.com/2010/01/03/method_exists-vs-is_callable/ One thing I often see when re-factoring PHP applications, is the improper use of the method_exists() function, and I think this needs a little bit of clarification.

Here is a typical example of what I’m talking about:


if (method_exists($object, 'SomeMethod'))
{
  $object->SomeMethod($this, TRUE);
}

The purpose of this code snippet is quite easy to understand (even if I don’t encourage to do this kind of not-very-OOP-stuff): having an object named “$object”, we try to know if it has a method named “SomeMethod”, if so, we call it, and provide some arguments to it.

Yes, but…

This code will probably run very well during all its lifetime, but what if the object’s method is not visible from the current scope (like… a private or protected method)? PHP’s method_exists() function does what it says: it checks if the provided class or object has a method named like the provided one, and returns TRUE if so, or FALSE if not, visibility is not questionned. So, if you provide a private or protected existing method name (being out of current scope) to method_exists(), you’ll get TRUE as the return value, and a nice “Fatal error: Call to private method…”, immediately terminating the current script execution.

The right tool for the right job

The real intent of the previous code snippet was in fact to know if the application could call a method on the object, from the current scope.

This is why (among other reasons) is_callable() is part of the PHP built-in functions.

How does it work?

is_callable() receives a callback as its first argument, which, in our case, consists of an array of two values: the first being an object (or a string holding a class name), and the second being a string holding a method name. is_callable() returns TRUE when the provided callback can be called from the current scope, or FALSE if not.


if (is_callable(array($object, 'SomeMethod')))
{
  $object->SomeMethod($this, TRUE);
}

Here is another snippet of code to illustrate the differences between method_exists() and is_callable() in action:

class Foo {
  public function PublicMethod() {}
  private function PrivateMethod() {}
  public static function PublicStaticMethod() {}
  private static function PrivateStaticMethod() {}
}

$foo = new Foo();

$callbacks = array(
  array($foo, 'PublicMethod'),
  array($foo, 'PrivateMethod'),
  array($foo, 'PublicStaticMethod'),
  array($foo, 'PrivateStaticMethod'),
  array('Foo', 'PublicMethod'),
  array('Foo', 'PrivateMethod'),
  array('Foo', 'PublicStaticMethod'),
  array('Foo', 'PrivateStaticMethod'),
);

foreach ($callbacks as $callback) {
  var_dump($callback);
  var_dump(method_exists($callback[0], $callback[1])); // 0: object / class name, 1: method name
  var_dump(is_callable($callback));
  echo str_repeat('-', 40), "\n";
}

Run it, and you’ll see that every test returns TRUE with method_exists(), even private methods, while is_callable() returns FALSE for these (and will also trigger strict errors with non-static methods being queried as static ones, be aware of this).

More details

is_callable() has other uses, like checking the syntax of the provided callback, without checking if there really is a class or a method with the provided names.
Like method_exists(), is_callable() can trigger a class autoloading process if the provided class is not already loaded.
If an object has the magic __call() method implemented, then is_callable() will return TRUE for any non-existent method, while method_exists() will return FALSE. I guess the same behavior can be observed with the recent (PHP 5.3.0) __callStatic() magic method, but I did not test it (yet).
Everything else you need to know is in the PHP manual.

]]>
http://blog.jmfeurprier.com/2010/01/03/method_exists-vs-is_callable/feed/ 4
Simple introduction to SVN externals http://blog.jmfeurprier.com/2009/12/10/simple-introduction-to-svn-externals/ http://blog.jmfeurprier.com/2009/12/10/simple-introduction-to-svn-externals/#comments Thu, 10 Dec 2009 20:36:34 +0000 Jean-Michel Feurprier http://blog.jmfeurprier.com/2009/12/10/simple-introduction-to-svn-externals/ Not so long ago, we’ve had to include a third-party library into a new project (using SVN). Our first idea (the one which did not imply thinking) was to SVN-export library files from the remote repository, paste them into the project, SVN-add them, then SVN-commit files.

Having to keep these library files up-to-date with official patches and improvements sounded like a full-time job.
This solution sucked.
A lot.

We are programmers, and we really hate repetitive tasks because we are lazy. We spend most of our time building applications which automate human tasks, why not take care of this one?

Good news, a quick googling revealed our issue was a common one, and there was already a ready-to-use solution: SVN externals.

What are SVN externals?

SVN externals allow to include (nest) a remote SVN repository into another SVN repository. They are set through SVN properties.

How to use them?

If you’re a command-line geek, type:

svn propset svn:externals "http://svn.3rdapp.com/super-library/ library" .

This will create a SVN property at the current location (don’t miss the final dot “.” at the end) named “svn:externals”, and its value will be “http://svn.3rdapp.com/super-library/ library”. Which means: insert a directory named “library”, which will retrieve its content from a distant SVN repository located at “http://svn.3rdapp.com/super-library/”. The next time you run a SVN-update, the third-party files will be added to your SVN project.

You can do the same with TortoiseSVN Windows Shell Extension for Subversion: right-click when browsing your SVN project with the Windows file explorer, highlight “TortoiseSVN”, then click “Properties”:

SVN externals: TortoiseSVN, step 1

Now, click “New…”, type or pick “svn:externals” in the “Property name:” drop-down, then type “http://svn.3rdapp.com/super-library/ library” in the “Property value:” textarea. Click “OK” twice:

SVN externals: TortoiseSVN, step 2

Now, every time a new version of the third-party application will be released, it will be reflected when you SVN-update your local copy of your project.

]]>
http://blog.jmfeurprier.com/2009/12/10/simple-introduction-to-svn-externals/feed/ 0
Improving performance with return values caching http://blog.jmfeurprier.com/2009/02/04/improving-performance-with-return-values-caching/ http://blog.jmfeurprier.com/2009/02/04/improving-performance-with-return-values-caching/#comments Wed, 04 Feb 2009 06:26:29 +0000 Jean-Michel Feurprier http://blog.jmfeurprier.com/2009/02/04/improving-performance-with-return-values-caching/ Many functions (and methods) in a project will often provide the same return value for the same arguments, like:

  • mathematical functions:
function SomeMaths($x)
{
	return $x + pow($x, 3.2) - cos($x);
}
  • functions which retrieve content from a file:

function GetConfiguration()
{
	return parse_ini_file('configuration.ini');
}
  • functions which retrieve content from a database:
function GetArticleById($id)
{
	$sqlId  = mysql_real_escape_string($id);
	$result = mysql_query("SELECT `id`, `title` FROM `article` WHERE `id` = '$sqlId' LIMIT 1");

	if (FALSE === $result)
	{
		throw new Exception('Query failed.');
	}

	return mysql_fetch_assoc($result);
}

If your project holds a function like one of these, and:

  • your prefered profiling tool reveals that a lot of the execution time is spent in this function
  • its returned value is always the same during a single run (script execution), when providing the same arguments
  • this function is called more than once per run

Then consider caching (saving) its return values.

Here is how it can be achieved (yes, there are more advanced techniques to do it, but this is not the point of this post): add a static variable in the body of the function, which will hold an associative array, mapping every parameter combination with a return value:

function GetArticleById($id)
{
	static $cache = array();

	// Return value is not in cache yet?
	if (!isset($cache[$id]))
	{
		$sqlId  = mysql_real_escape_string($id);
		$result = mysql_query("SELECT `id`, `title` FROM `article` WHERE `id` = '$sqlId' LIMIT 1");

		if (FALSE === $result)
		{
			throw new Exception('Query failed.');
		}

		// Add return value to cache
		$cache[$id] = mysql_fetch_assoc($result);
	}

	// Return cache content
	return $cache[$id];
}

Here it is, the (possibly heavy) process of querying the database will only be executed once at the first function call. Every other function call with the same argument will use the cached return value.

Keep in mind that the amount of cached return values must be reasonable (available memory is limited). If there are millions of possible arguments combinations for a function in a single run, you’ll have to consider a more elaborate way of optimizing it (this could be the subject of a future post).

Also, always, always, ALWAYS profile your code BEFORE you decide to apply an optimization like this one (and wait for your project to be nearly completed before profiling).

]]>
http://blog.jmfeurprier.com/2009/02/04/improving-performance-with-return-values-caching/feed/ 5