Setting Vagrant with Yii PHP

vagrant

As everyone is talking about start using Vagrant, I’m writing this post about how you can use it for Yii and customize it for other projects written in PHP.

I’m not going to tell you why are we using Vagrant, bit far point less, if some of you is interested why we need it than please look at their offical site,
Here we just want a standard development environment every team developer can use and work with it.

Have a look at what we are going to do today! it will just take few minutes 🙂

1. Installing Vagrant
2. Installing VirtualBox
3. Setting up Vagrant with my favorite box
4. Provisioning with Vagrant
5. Setting up Apache, PHP 5.X, Mysql 5.X and othe things

last but not least we need a working copy of yii framework, where you are developing your app!

1. Installing Vagrant
I’m using Ubuntu 12, I’m not going to run through how to do this in every operating system because it is out of the scope of this tutorial.
So the first thing to do is to head over to the downloads page of Vagrant and install the version fits for your operating system.
Once fully installed, the command vagrant is now available to use in your favorite terminal.

2. Installing VirtualBox
Another requirement to use Vagrant is that you have a Virtual Machine provider. This is basically just software that runs the virtual machine. I’m going to be using VirtualBox because it’s free and easy to set up. After installation you don’t need to check as much. Lets proceed!

3. Setting up Vagrant with my favorite box
Now the fun part has arrived! Vagrant is basically just a configuration file (Vagrantfile) that tells the VirtualMachine what to set up and in the end what to run. The Vagrantfile should be kept in the root of your project and should be added to Git so that anyone else who is working on the project can use the same configuration file.
Lets open our favorite terminal and move to the working directory where your project is setup.

cd /var/www/project/stowitt/front-panel/

now do:

vagrant init

Now if you open your project in a text editor, you will see the new Vagrantfile into your project.

Next thing is your need is box. When you are setting up a Virtual Machine, you need the operating system and all of that junk before you even begin. Operating system is the Vagrant box here, Vagrant provides base images of those operating system.
To download an Ubuntu box, run the following command:

vagrant box add precise32 http://files.vagrantup.com/precise32.box

Once done add the following lines to your Vagrantfile:

config.vm.box = "base"
config.vm.box = "precise32"

Now it knows which box to use and your machine is just ready?? wanna try! run the command in terminal:

vagrant up

You should see a load of output to the terminal. Vagrant doesn’t actually have a user interface so you will see only the output of every command. Now to see what is going on you can do SSH, similar to your production environment.
While it’s up do:

vagrant ssh

You are not into the virtual machine! You can do anything you want but lets type “exit” and return for now.

After ended up working on machine, we can shut it down by using the following command:

vagrant destroy

Now lets do this back:

$ vagrant up
$ vagrant ssh
$ cd /vagrant
$ ls -l

You should see a list of all the files from your project. Vagrant will automatically sync all of the files from the root of the project. Pretty cool!

4. Provisioning with Vagrant

If you have ever set up a fresh installation of Ubuntu, you will know that you have to install a load of things before you are good to go. Now that you can SSH into your machine, you can happily go about installing whatever you want to set up the machine exactly how you want it.

To set up provisioning, all we have to do is to create a shell script that will automatically be loaded when we boot up Vagrant.

Create a new file called bootstrap.sh in the root of your project (the same location where you saved Vagrantfile).

Next we need to tell Vagrant to run this file when it starts up. Open your Vagrantfile and add the following line under where you set the box:

config.vm.box = "precise32"
config.vm.provision :shell, :path => "bootstrap.sh"

Now that we have provisioning set up, we can start adding a list of instructions for what should be provisioned whenever Vagrant is set up.

5. Setting up Apache, PHP 5.X, Mysql 5.X and othe things

Now we are ready to install anything we want on our virtual development machine. To be specific about PHP and specially Yii we are going to install these items one by one.

Open up your boostrap.sh file and add the following:

#!/usr/bin/env bash

Now lets update Ubuntu:

apt-get update

You need to add these lines in bootstrap.sh as we go!!!

Install Vim:

apt-get install -y vim

Set up Apache:

apt-get install -y apache2
# Remove /var/www default
rm -rf /var/www
# Symlink /vagrant to /var/www
ln -fs /vagrant /var/www
# Add ServerName to httpd.conf
echo "ServerName localhost" > /etc/apache2/httpd.conf
# Setup hosts file
VHOST=$(cat <<EOF
<VirtualHost *:80>
  DocumentRoot "/vagrant/public"
  ServerName localhost
  <Directory "/vagrant/public">
    AllowOverride All
  </Directory>
</VirtualHost>
EOF
)
echo "${VHOST}" > /etc/apache2/sites-enabled/000-default
# Enable mod_rewrite
a2enmod rewrite
# Restart apache
service apache2 restart

Install PHP 5.X:

apt-get install -y libapache2-mod-php5
apt-get install -y python-software-properties
add-apt-repository ppa:ondrej/php5
apt-get update

Set up other PHP stuff:

# Need sudo to run the following, adding root password as "Crazy007Fox"
sudo passwd
Crazy007Fox
sudo
Crazy007Fox
apt-get install -y php5-cli
apt-get install -y php5-mysql
apt-get install -y php5-curl
apt-get install -y php5-mcrypt

Install cURL:

apt-get install -y curl

Install MySQL:

export DEBIAN_FRONTEND=noninteractive
apt-get -q -y install mysql-server-5.5

Install Git:

apt-get install git-core

Set up Yii:

# setup database:
echo "CREATE DATABASE IF NOT EXISTS yii_app" | mysql
echo "CREATE USER 'root'@'localhost' IDENTIFIED BY ''" | mysql
echo "GRANT ALL PRIVILEGES ON yii_app.* TO 'yii_app'@'localhost' IDENTIFIED BY ''" | mysql
# run migration
cd /var/www/
yiic migrate
# give write permission to some directories
sudo chmod -R 777 /var/www/assets/
sudo chmod -R 777 /var/www/protected/runtime/

 

Final Run

Now everything got setup, but hey! how do I run the project from virtual machine. Well Vagrant makes this really easy with it’s port forwarding feature. This simply allows you to specify ports on the guest machine to share via a port on the host machine.

Add the following line to your Vagrantfile:

config.vm.network :forwarded_port, host: 8090, guest: 80

now start your machine with vagrant up
vagrant up

Once done, on your local machine try:

http://localhost:8090 in your browser to see your project.

Checkmate you are done with your virtual machine setup and your site is running 🙂

Advertisements

25 Tips to Optimize Your Code

Initially I had a chance to write code optimization techniques as a hunt of compiler construction in C++ and later I decided to do this specifically for web programing languages, as I have been working on Python, Perl and Ruby to figure out which language can be better to write applications that executes faster.
I personally found Python to be better in performance then PHP, Perl or Ruby. However If you are still a PHP developer or generally write web code these 25 tips can help you lot in terms of writing fast and memory efficient applications.

1. Upgrade Your Distribution
Simply upgrading your distribution like PHP, is without a doubt one of the easiest ways to improve PHP performance. In addition to the usual bug fixes and new features, each new PHP release ships with optimization improvements which can produce noticeable performance enhancements.

2. Use Native Functions
As much as possible, try to use native PHP functions rather than writing your own functions to achieve the objective. For example, you can use range( b, k) to get an array of alphabets starting from b to k in sequence, if it is only needed once in the script rather than declaring an array with these values in a function and returning it on its call.

3. Take Advantage of Native Extensions
PHP has long been accused of including everything but the kitchen sink, and in recent years the development team has made great strides in terms of stripping the core distribution of optional and redundant features (such as deprecating the redundant POSIX Regex library in preference of the PCRE library). Even so, the sheer number of available libraries and other extensions can be overwhelming, leading some developers to consider implementing their own solutions rather than invest the time investigating what’s already available.
For instance it might be tempting to spend a few hours writing a custom library capable of parsing XML, despite the availability of SimpleXML. Doing so ignores the many hours of troubleshooting and optimization already put into the native extensions, thereby almost guaranteeing the substandard outcome of any such custom solution. For this reason and others you should always investigate the availability of an existing library or extension before setting out to reinvent the wheel.

4. Use a PHP Accelerator
Barring outside interference, a PHP script executes after being “compiled” by the PHP engine, which turns the PHP code you’ve written into machine language, known as operation code (opcode). If the PHP script repeatedly churns out an identical result, then why not skip the compilation process altogether?
You can do exactly this using a PHP accelerator, which caches a PHP script’s compiled machine code, allowing the code to immediately execute upon request rather than after a potentially expensive compilation process.
Several opcode caching solutions are available to PHP developers, including notably APC (Alternative PHP Cache), an open source accelerator available for installation via PEAR. Another popular solution is Zend Server, which incorporates not only opcode caching, but also full and partial page caching utilities.

5. Use Late Static Binding
If a method can be static, declare it static. Speed improvement is by a factor of 4. As of PHP 5.3.0 Late static binding introduced, a new use for the static keyword, which addresses this particular shortcoming. When you use static, it represents the class where you first use it, ie. it ‘binds’ to the runtime class.
For example this will blow the code execution:

abstract class Builder {
    public static function build() {
        return new static;
    }
}
class Member extends Builder {
    public function who_am_i() {
        echo 'Member';
    }
}
Member::build()->who_am_i();

6. Performance of FOR vs FOREACH in PHP
My personal opinion is to use what makes sense in the context. Personally I almost never use for for array traversal. I use it for other types of iteration, but foreach is just too easy… The time difference is going to be minimal in most cases.
For some reasons I decided to do a quick benchmark run…

$a = array();
for ($i = 0; $i < 10000; $i++){
$a[] = $i;
}

$start = microtime(true);
foreach ($a as $k => $v){
$a[$k] = $v + 1;
}
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v){
$v = $v + 1;
}
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => $v) {}
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {}
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

And the results:
Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds

So if you’re modifying the array in the loop, it’s several times faster to use references…

7. Frequently Used Switch Cases
Keep most frequently used switch cases on the top. A switch statement is not always faster than an if statement. It scales better than a long list of if-else statements as switch can perform a lookup based on all the values. However, for a short condition it won’t be any faster and could be slower.

8. Conditions that uses = = =
Use “= = =” instead of “= =”, as the former strictly checks for a closed range which makes it faster.

9. Pass Reference to Function
Pass reference to the function if it does not affect your logic. A function manipulating the reference is faster than those manipulating the value been passed as here one more copy of the value is getting created. Especially it adds overhead when the value passed by you is a big array.
For example, let us create a function in two different way to increment by 1, each element of an array having values 0 to 99.

// passing by reference
function  computeValue( &$param )
{
// Something goes here
foreach( $param as $k => $value)
{
$param[$k] = $value + 1;
}
}
$x = array();
for( $i =0; $i<99; $i++)
{
$x[$i] = $i;
}
computeValue( $x);

// array with 100 elements each incremented by 1
print_r( $x );

The function above works faster than the function below although both will produce the same result ( increment each element of the array by 1. )

// passing by value
function  computeValue( $param )
{
// Something goes here
foreach( $param as $k => $value)
{
$param[$k] = $value + 1;
}
return $param;
}
$x = array();
for( $i =0; $i<99; $i++)
{
$x[$i] = $i;
}
// array with 100 elements each incremented by 1
print_r(computeValue( $x));

10.    Use Caching Techniques
Use cache to reduce the load of database operations as well as the script compilation. We can use memcache for the reducing database load and APC for opcode caching and intermediate code optimization.

11.    Use Single Quotes
Using single quotes ( ‘ ‘ ) is faster than using double quotes( ” ” ) if you are going to keep only the string inside it avoiding any variables. Double quotes checks for the presence of variable and adds little bit of overhead.

12.    Use Appropriate String Functions
str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4.

13.    Calculate Only Once
Calculate and assign the value to the variable if that value is getting used numerous time rather than calculating it again and again where it is being used.
For example, the following will degrade the performance.

for( $i=0; i< count($arrA); $i++)
{
echo count($arrA);
}

The script below will perform much better.

$len = count($arrA);
for( $i=0; i< $len; $i++)
{
echo $len;
}

 

14.    Disable Debugging Messages
File operations are a bit expensive if you are using it quite often in code. So, if you are calling lot of custom functions to log errors and warning during your development process, make sure you remove them before you push the code to production.

15.    Use Methods in Derived Classes
Methods in derived classes are faster than base classes. For example, let there be a function in both base class and derived class for performing task1. It is named as “forTask1? in base class and “forTask1again” in derived class, so that they will not override.
Call to the function “forTask1again( )” which is in derived class will work faster than call to the function “forTask1( )” as it is from base class.

class someBaseClass
{
public function forTask1($string)
{
// perform task 1
}
public function forTask2( )
{
// perform task 2
}
}

class derivedClass extends someBaseClass
{
public function forTask1again($string)
{
//perform task 1 same as the function in base class.
}
public function forTask3($string)
{
//perform task 3
}
}

//Instantiating the derived class below.
$objDerivedClass = new derivedClass( );

// The call below works slow for task1 as it is from base class.
$resultTask1 = $objDerivedClass->forTask1( );

// The call below works faster for task1 as
// it is from derived class.
$sameResultTask1 = $objDerivedClass->forTask1again();

 

16.    JSON Vs. XML
Use JSON instead of XML while working with web services as there are native php function like json_encode( ) and json_decode( ) which are very fast. If you are bound to have XML form of data, then use regular expression to parse it instead of DOM manipulation.

17.    Use isset
Use isset( ) where ever possible instead of using count( ), strlen( ), sizeof( ) to check whether the value returned is greater than 0.
For example, let us assume that you have a function which returns an array with values or a NULL array. Now you want to check whether the returned array is with values or not, then use the following:

if(isset($returnValue))
{
// do something here
}
In this case, use the above code block, instead of the following:
if(count($returnValue) > 0)
{
// do something here
}

 

This will also be fast to execute:

// Checking if string length is 5
if(isset($foo{5}))
{
}

18.    Pre increment vs Post increment
Well, increment a certain value also have a few ways to improve. We all know that there are many ways to increment integer values such as – See more at:

$i++;
$++i
$i+=1;
$i = $i + 1;

Out of all these what way is the most efficient? In PHP, it seems like pre increment is better than the other ways of performing an increment. Its around 10% better than post increment? The reason? Some said that post increment made certain copy unlike pre increment. There isn’t any benchmark done for PHP but i found one on C++ which should be quite the same. Well, without a proper benchmark on this, i can’t really confirm this. Furthermore, it really doesn’t makes a big differences towards normal programmers but may affect those who are working towards micro optimization.  Nonetheless, many people do suggest pre over post increment in term of optimization.

19.    Absolute Path VS Relative Path
Absolute path which is also known as full path compare to a relative path which will be better for PHP? Surprisingly, it seems that absolute path is better. Compare to relative path which might just help to screw up your include and require operation in PHP, absolute path doesn’t. Well, that’s the reason why i use absolute path. But the real reason is that using absolute path eliminate the need for the server to resolve the path for you. Simply to say, do you know where the file is located when you just look at a relative path or is it faster if i just throw you the full path?

20.    Dot Vs Commas Concatenation
Between dot and commas which way do you use to concatenate between two strings/variables? I personally used dot to concatenate my stuff. Such as the one shown below:

$a = '10 PHP programming ';
$b = 'Improvement Tips';
#10 PHP Programming Improvement Tips
echo $a.$b;

I usually do the above. Instead of this,

$a = '10 PHP programming ';
$b = 'Improvement Tips';
#10 PHP Programming Improvement Tips
echo $a , $b;

21.    use gzip compression
Use ob_start() at the beginning of your code. This gives you a 5-15% boost in speed for free on Apache. You can also use gzip compression with ob_gzhandler() for extra fast downloads (this requires spare CPU cycles).

22.    Use unset in larger scripts
unset() variables that are not used anymore to reduce memory usage. This is mostly useful for resources and large arrays.

23.    Reduce Number of Hits to DB
Try to reduce the number of hits to the database. Make queries aggregate so that you call the database less number of times. For example:

$con=mysqli_connect("localhost","username","somepassword","anydb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL" ;
mysqli_connect_error();
}
function insertValue( $val ){
mysqli_query($con,"INSERT INTO tableX (someInteger) VALUES ( $val )");
}
for( $i =0; $i<99; $i++){
//  Calling function to execute query one by one
insertValue( $i );
}
// Closing the connection as best practice
mysqli_close($con);

The script above is much slower than the script below:

$con=mysqli_connect("localhost","username","somepassword","anydb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL" ;
mysqli_connect_error();
}
function insertValues( $val )
{
// Creating query for inserting complete array in single execution.
$query= " INSERT INTO tableX(someInteger) VALUES .implode(',', $val)";
mysqli_query($con, $query);
}
$data = array();
for( $i =0; $i<99; $i++)
{
// Creating an array of data to be inserted.
$data[ ]  =   '(" ' . $i. '")' ;
}
// Inserting the data in a single call
insertValues( $data );
// Closing the connection as a best practice
mysqli_close($con);

24.    Tune your Database
Tune your database and index the fields that are commonly used in your SQL WHERE criteria. ADOdb, the very popular database abstraction library, provides a SQL tuning mode, where you can view your invalid, expensive and suspicious SQL, their execution plans and in which PHP script the SQL was executed.

25.    For MySQL use relevant Storage Engine
Distribute your tasks into reading or writing. Use relevant Storage Engine for reading and writing. Slow writing can go to background process. Use temporary tables to boost writing.