The Deployer

July 25, 2009

Migrating a Subversion (SVN) repository

Filed under: Featured Articles, Subversion — Tags: , , , — Lucian Daniliuc @ 10:18

Recently I have a brand new stand-alone server for my repositories and other minor thingies. And the challenging thing: moving the repositories from my home desktop computer to this server.

My setup was this: I have my home desktop computer that runs Windows XP, and the repositories were stored and managed using VisualSVN, a great tool to manage SVN repositories, if you’re running Windows. The applications were deployed on my Windows machine (for developing purposes) and on the hosting server (live, production deployment) that runs Linux. And here’s what I’ve done…

On the source, Windows machine

I’ve stopped the SVN service, so no svn updates/commits would be initiated. I’ve opened up a console and ran the following command:
svnadmin dump d:\Repositories\repo_a > repo_a.dump

Then I’ve packed the repo_a.dump file because it’s almost plaintext and copied the archive to the destination server.

On the destination, Linux machine

I’ve unpacked the dump file and then:
svnadmin create repo_a
svnadmin load repo_a < repo_a.dump

After that, I needed to chown -R www-data:www-data ./* to make the files belong to apache, and then add the authentication back.

This is just about it for the relocation of the repositories. But we need to do one more thing: alter all the checkouts to point to the new repositories. This is done in a way on a Windows machine, and a bit different on a linux machine.

Checked out repositories fixing

To make all the deployed checkouts point to the new server, you need to edit every file called "entries" that is located in every ".svn" folder of a checked out repository.

To do that, on Windows you can use grepWin, a lovely tool that does all the work:

grepwin

There you have it. On linux, you'll need perl:
find ./ -name "entries"|xargs perl -w -i -p -e "s/svn\.example\.com/new\.server\.com/g"

This command replaces all the occurences of "svn.example.com" with "new.server.com" in all the files named "entries" in the current folder and below. Replace for your own needs.

April 14, 2009

Why should we use PHP constants inside classes

Filed under: Featured Articles, PHP — Tags: , , — Lucian Daniliuc @ 22:58
constant
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren’t actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

Practically, it’s as easy as:

define('DATABASE', 'thedatabase');

Constants are useful in a lot of cases:

  • Configuration directives

    Storing database connection information is plain easy and available everywhere.

    define( 'DATABASE', 'thedatabase' );
    define( 'USERNAME', 'theuser' );
    define( 'PASSWORD', 'thepass' );
    define( 'HOSTNAME', 'localhost' );

    These have global scope, cannot be tempered with and can be accessed from everywhere. How easy is that?

  • Anti-hack techniques

    You can make sure nobody accesses and uses your files remotely by checking a constant that you only define in one place, unaccessible from the web.

    if(!defined('ANTIHACK_FG3N4890FN4334G3GH')) die('You naughty');
  • Various flags

    Usually you need here and there to set some flags that activate or dezactivate some functionalities in your application, including debug flags.

    define('USE_CACHE', true);
    //.... some code....
    if(constant('USE_CACHE')) {
      //... cache data here
    }

    By using

    constant()

    , we don’t get a notice if the constant is not defined, and to disable the cache, you can take any approach you find suited: either set the defined constant to “false”, or comment it, the outcome is the same and you don’t get notices and warnings in your code, even if you completely remove the constant from your code.

So, you define the constants with define(), you check to see if certain constant is defined with the defined() function and you get the value of a constant that could or could not be defined using constant().

Using constants in classes

Along with the wonders of OOP in PHP 5 came the possibility to define constants inside classes. For example:

class AppSettings {
	const DATABASE = 'thedeployer';
	const HOSTNAME = 'localhost';
	const USERNAME = 'deployer';
	const PASSWORD = 'thepassword';
 
	public function __construct() {
		echo 'database = `' . self::DATABASE . '`';
		echo 'hostname = `' . self::HOSTNAME . '`';
		echo 'username = `' . self::USERNAME . '`';
		echo 'password = `' . self::PASSWORD . '`';
	} // END constructor
} // END class
 
echo 'database from outside = ' . AppSettings::DATABASE;

Basically, the constants ar a part of the class definition, you don’t have to actually execute code to define the constants and they are available immediately for use. And most important, you don’t have to instantiate a class to access it’s constants, and you always know where to look for the definition.

The advantages and differences that one should remember when using constants and the reasons to use constants in classes rather than just floating around in your code are:

  • Constants defined in classes do not show up in the global scope.

    There is a stack where PHP holds all the constants and it’s a rather large list. It’s nothing like the variables which are a total of 4 superglobals that exists when a script starts. To see the list of defined constants, just run:

    print_r(get_defined_constants());

    You’ll get a huge list of approximately 1760 defined constants when your script hasn’t got a line. This is a required compromise, because these constants include TRUE, FALSE, error codes, constants defined by enabled extensions and some other useful constants. This is why your constants shouldn’t go here. If you define your constants as part of some classes, they remain within the class definition and don’t end up in the constants pool. And don’t worry, even if they’re defined within a class, they are available everywhere, just like a normal constant.

  • Grouping the same type of data together.

    Usually, you can define a class that just deals with every piece of configuration data your application needs, just like de example above. This means that all your constants are in one place, and if you need to change a constant, you only need to find where the class is defined and change your info. You even have the class name, because you’ll be using the constants defined in some class this way:

    echo 'database from outside = ' . AppSettings::DATABASE;
    // this means that the "DATABASE" constant is defined in the "AppSettings" class.

    How easy is that?

  • Available without executing code.

    Since the constants are part of the class definition, they’re available before even the first line of actual code is executed.

  • Class autoloading power.If you have the autoload feature in use in your application, you’ll get another advantage. You’ll have the constants defined with a single call to the wanted class that contain the constants. The autoloader will locate an load you class.

These are just a few things that need to be said and noted when addressing constants. Be careful not to use constants where they’re not appropriate. For example in internationalization. Don’t define the i18n labels in constants. That’s a very greedy approach. Use gettext extension or some other dedicated solution for this. Using constants is just bad.

Happy coding and have a nice day!

April 9, 2009

Unlocking (jailbreaking) your iPhone 3G (2.2.1)

Filed under: Featured Articles, iPhone — Tags: , , — Lucian Daniliuc @ 21:17

The background and “the why?”

Apple has a very evolved sense of security and thus you won’t be able to install any application not listed in the AppStore. In order for you to be able to install WinterBoard (a replacement for that main menu), themes, sounds, ringtones, wallpapers and all those goodies, you need to jailbreak your iPhone which means you have to make it be able to install any software you choose.

Each time you update to a new firmware version, a new QuickPWN tool is necessary. This article covers the update to 2.2.1, but it is exactly the same for any older version (I’ve tried them all).

Warning! This is not the same as unlocking your phone, which means making it work with any GSM operator out there. This article is not about this. Unlocking is illegal, while jailbreaking is legal and usually doesn’t break your warranty.

How to jailbreak your iPhone

1. Update

The first thing to do is have the latest version of iTunes installed in order to update your iPhone to the latest firmware. Just connect it to a internet-enabled computer with iTunes and you’ll instantly get the message to download and install the latest firmware, if you haven’t done so already.

2. Get the tool

Go to  http://www.quickpwn.com/2009/01/official-quickpwn-221-and-pwnagetool-jailbreak-for-windowsmac.html and download QuickPWN 2.2.1 for Windows. It’s small piece of software that does exactly this: jailbreak your phone.

QuickPWN Official website

QuickPWN Official website

When the 3.0 version will be out, this is where you should come and get the latest version.

A word of caution. I’ve seen that fresly releases of QuickPWN tools for fresh firmware versions are not fail-proof and you may run into trouble. You should wait for at least a month before jailbreaking your phone after a new version is released just to make sure that most of the bugs are identified and fixed. That is what I do.

3. Start the tool

Have the iPhone connected via USB cable to the computer and fire up the downloaded QuickPWN tool. It will show up like this:

QuickPWN Tool startup screenshot

QuickPWN Tool startup screenshot

Do not worry, the procedure is easy and it’s very unlikely that something will go wrong.

4. Firwmare file

Select the upgraded firmware. Once iTunes upgrades your iPhone firmware version to 2.2.1, it automaticaly saves the firmware somewhere on your drive. QuickPWN tools needs this file in order to patch it and reapply it to your iPhone.

If you have the file, is already selected in the textbox, if not, you can download it from here. After selecting it, or if you already had it selected, a progress circle starts spinning telling you that he’s working on patching the selected file. It does it in some backup file, so have no fear.

QuickPWN select firmware page

QuickPWN select firmware page

5. Touching the firmware file

After the tool patches the firmware file, you’ll see a big checkmark next to the phone picture. Click on the left arrow to go to the next step.

QuickPWN patched the firmware successfuly

QuickPWN patched the firmware successfuly

6. Select what you wish to install

Installing application will still be done from the iPhone, but there are two very nice applications to help you in doing that: Cydia and Installer. You should leave them both checked and go to the next page.

QuickPWN selecting Cydia and Installer

QuickPWN selecting Cydia and Installer

7. Check the USB connection

This is where things will start to be applied to your phone and for that check that the phone is correctly connected to the PC and click next.

QuickPWN checking the USB connection

QuickPWN checking the USB connection

During the jailbreaking you will be asked to keep the Start button pressed for a few seconds, then (while still keeping the Start button pressed) you will be asked to also push and keep pushed the power button for a number of seconds, and then, without releasing the Start button, to release the Power button and keep the Start button pressed for some more seconds.

Don’t panic, even if you don’t get it right the first time, you cand just try and try again. Just have your fingers correctly positioned and click next. This operations are required to put your iPhone in firmware upgrade mode, which cannot be done by software.

8. The jailbreaking

This is where the real process starts. As the iPhone connects in Recovery Mode you’ll see the firmware upgrade indicated on your phone.

iPhone in Recovery Mode

iPhone in Recovery Mode

After entering Recovery Mode, the jailbreaking procedure will start:

QuickPWN jailbreaking your iPhone

QuickPWN jailbreaking your iPhone

While the jailbreaking is in progress, your iPhone will show this screen:

QuickPWN jailbreaking almost complete.

QuickPWN jailbreaking almost complete.

This is going to take a few minutes. Don’t worry, this is perfectly normal.

Just before it ends, your iPhone will restart and show up a progress bar indicating the final touches:

QuickPWN reboots the iPhone and adds the final touch.

QuickPWN reboots the iPhone and adds the final touch.

9. Hurray! Your iPhone is out of it’s cage, and you can start benefiting from the tons and tons of applications, games, utilities and themes out there. How to install applications by using Cydia and Installer will be the subject of another article.

DISCLAIMER: I am not responsible if, for whatever reason, your phone, PC, ego or anything else is damaged or harmed in following this how-to. People all around the world jailbreak thousands of iPhones and have no problems, but you may have, for no apparent reason. Do this on your own risk!

March 29, 2009

APC – Alternative PHP Cache

Filed under: Featured Articles, PHP — Tags: , , — Lucian Daniliuc @ 23:53

APC is a simple and yet powerful PHP extension that does just that: caching. What for? Suppose you would have some piece of code that fetches some data from a table, and since you don’t use JOIN because you loose scalability, you’ll have to do some more SELECTs, and then format each row to be ready for display.

The other advantage is that it caches the compiled PHP source code in memory, serving it a lot faster.

Now if 100 users to this in one minute, (1) your server will fail to serve the pages because (2) it is doing a very complicated task that outputs the same result throughout the minute. This is where APC comes handy. You can save the retrieved data in the APC cache which holds it in memory and then just serve it to whoever asks for it.

The first thing to do is check if the APC extension is installed and running. For that you can look at phpinfo()’s result and check for APC. If it’s not, you should look in the php.ini file for the extension directive to be uncommented.

Using the APC cache requires three things:

  • a name (key) for the piece of information saved;
  • the actual data;
  • the TTL (time to live): how many seconds the information will be held in the cache.

The syntax to add data in the cache is as follows:

bool apc_add ( string $key, mixed $var [, int $ttl=0] )

So, $key is the name under which we’ll find the saved info, $var is the actual data and $ttl is an optional parameter to specify a time to live. If this function returns FALSE, something went wrong and the information isn’t cached. You’ll have to have some sort of fallback and never rely on the fact that you’re info is safe in the cache.

To retrieve the cached data, use apc_fetch():

mixed apc_fetch ( string $key [, bool &amp;$success ] )

It’s that easy. Just ask for the saved key and you get it. If it’s not found or something goes wrong, this function returns FALSE and if the optional parameter was specified, sets that one too to FALSE.

That’s it. You have an up and running cache system.

Good practice: Regarding the usage of cache, there are two things you should keep in mind:

  1. you should build your code like there can be no caching done; that means 100% fallback. If the APC extension is disabled, your code should work.
  2. the specific APC caching functions should be wrapped up in some generic functions that call the actual functions. This thing will make you go light up a candle when – at some point – you’ll be switching to memcached or some other kind of caching, because you’ll only have to modify the contents of these wrapper functions, and not search & replace the entries in all your code.

Here’s an example on how to acomplish both these things:

function cacheWrite( $sKey, $mData, $iTtl ) {
  if( function_exists( 'apc_add ' ) ) { // we have APC
    return apc_add( $sKey, $mData, $iTtl );
  }
  return FALSE;
} // END func cacheWrite()
 
function cacheRead( $sKey ) {
  if( function_exists( 'apc_fetch' ) ) { // we have APC
    return apc_fetch( $sKey );
  }
  return FALSE;
} // END func cacheRead()
 
//---------- code that read/writes
 
$sKey = md5( $sQuery ); // same query will return same data, whithin minutes
if( ( $mData = cacheRead( $sKey ) ) === FALSE ) {
  // info not cached
  $mData = functionThatMakesUpTheData();
  cacheWrite( $sKey, $mData, 600 ); // cache the data for 10 minutes
}
// done, here we have our data, no matter if caching functions are available
// or not, if the info is in the cache or not

And to make it even more fun, APC comes with a nice online page that gives you all the information you need, including cache hits & misses (misses happen when the cache memory is full), a list of all the user-space cached data along with options to view or delete one or all the entries and much more.

September 26, 2008

Difference between identifying and non identifying relationship

Filed under: Featured Articles, MySQL — Lucian Daniliuc @ 17:51

A 1:M (one to many) non-identifying means that the associated record in the -one- table is not a parent of the associated record in the -many- table, but rather just related.

An example:

an identifying 1:M would be a building which has many rooms. The -one- table carries data about the building .. e.g., street address, number of floors, name. The -many- table carries data about the rooms in the building .. e.g., room number, capacity, special characteristics. The room cannot exist without the building, therefore this 1:M is an identifying relationship.

a non-identifying 1:M would be a DVD which has many renters. The -one- table carries data about the DVD… e.g., the movie name, the artist. The -many- table carries data about each person who rents that DVD .. e.g., name, price paid. The DVD can exist on its own, without ever having been rented, and the person can exist on her own, without ever having rented any DVD, therefore this 1:M
is a non-identifying relationship.

Donna Hinshaw

Source: http://lists.mysql.com/mysql/173538

Powered by WordPress