Archive

Archive for the ‘PHP Development Notes’ Category

What are some limitations of PHP?

By   | Comments off

Recently I answered a question on quora. I am reproducing it here again.

In my view question is not complete and does not provide context which has to be evaluated to answer.

So I am writing this answer based on two assumptions.

First of all I am assuming that questioner is evaluating few programming languages and wants to make a decision which language to use or learn?

One of the major feature of PHP is also its biggest limitation. It is loose type and does automatic data type conversion in most of the situations. It does not force you to be good. You can easily write a bad code and it will not give you any warning or notice, but this does not mean that you can not write good code in PHP. So if you ever found a good PHP programmer, praise him/her because he/she is doing good programming without being under a hunter of strict compiler or interpreter.

PHP is more suitable for web development and shell scripts (yes it is quite good at command prompt also). You should not consider this for desktop applications. PHP-GTK is available but still far away from being productive. So one limitation is lack of desktop application development support. You can also not do mobile programming although you can run PHP on an Android device start [PHP for Android]

PHP supports almost all good features and data types but it does not force you to use them (.. and falls back to default behavior) which sometimes can be source of bug introduction in your applications.

As far as leaning is concerned, PHP is easy but I will suggest learning another strong typed language like C or Java along with PHP (at least basic knowledge must be there) if you really wants to go to a good level in programming.

Second assumptions, I am making that questioner wants to gather points to do fight with the PHP guy on the block, in that case I would suggest, Please do not waste your time, No language is without some shortcomings in some specific context.

So choose your language based on your need. PHP is best in some cases and worst in some cases

PHP is growing and is on a fast lane in new features introduction, so we can hope that it will extends its reach to more different verticals in near future.

Drupal vs Zend : which one should be used for application development?

“You have done that specific site in Zend, don’t you think our application is also suitable for Zend instead of Drupal”, I just got this email from a prospective client.

This question has been asked to me many times. I am a big fan of Drupal as well Zend, so this question always put me in my difficult zone. As I know both, I really can not take a stand against any one of them. Technically speaking, both are capable of handing any kind of project, although both have their pros and cons.

drupal_zend_development

There is proverb, “All roads leads to Rome”. This same anatomy can be used in the tech decisions, if you are adamant about a technology you can do anything in that. Its just a matter of time and money, in short we can say its matter of resources. So I really can not state that a ‘particular’ task in not possible in Drupal or Zend. I can only state how much time a task will take in Drupal vs Zend or vice versa.

Lets try to analyze some of the common benefits of using Drupal and Zend. We will try to see which kind of application is suitable for Drupal or Zend.

Zend is a framework which provides MVC structure and many libraries to work with different components and services. These components and services allows you to build an application with ease. You can keep your concentration on the business logic and requirements of application instead of worrying about underline technical details of functional implementations.

Zend gives you a structure where you can implements many design patterns which you may have read in design pattern books. Using Zend you can directly use those classy patterns (thus takes benefits of them) in your applications without writing low level implementation code.

I am trying to enlist few requirements of  almost all applications and my views on them in regards to Drupal and Zend

Time frame

Turn around time for Zend application is usually higher than Drupal applications. In Drupal you have a running CMS with lots of available modules which  gives you functionality out of the box. So on time frame front Drupal scores really high.

Design
Zend applications has greater control over design aspects as it is programmed from scratch. Drupal on the other hand has a defined structure of elements which needs to used in certain ways. If you want to get rid of those structures, you may loose some benefits of drupal framework. Here Zend scores higher points as compared to Drupal, although a good designer with programmer support or programming knowledge can do wonders with Drupal. CSS manipulation is quite easy with Drupal.

Features Development

On this point, Drupal scores really higher as compared to Zend. Drupal has more than few thousands modules with different kind of functions. It also has concept of Site or Installation profiles where you can get a set bunch of modules for a particular use.

Zend on other hand is only a framework with libraries, it can help you to build applications but it can not gives you out of the box solutions. Zend version 2 has taken a big leap in this direction as module framework has evolved a lot with this release. So we can hope for some great modules in near future (We are also working on some such modules at our company which we will release in near future). There is another aspect of this feature, Drupal while having lots of modules also confuse potential customers or developers. They normally needs to do some hit and trial before they can get a good usable module.

Branding

When it comes to branding, Drupal scores less than Zend. Drupal being a CMS does have less respect in eyes of policy makers as compared to one which Zend enjoys. Zend seems to be perfect tailored solution while Drupal comes as something modified/managed solution. This is something which is beyond any technical explanation. So I will keep my views on this point with myself only. Just to state, I did not like such kind of perception building, but you can never argue with policy makers or people who has powers to take decisions.

Cost

As time frame is better with Drupal, it is obviously cheaper to build than Zend applications.

Most important factor in Drupal vs Zend decision is the requirement document of the application in hand. For example, application may be quite unique in its requirements, and you may not have any available module for it in Drupal. In this case, you loose time frame benefits.

So final decision should be taken with care with consultation with client.

 

I have given following reply to my this client

We have worked with both Zend and Drupal for different projects. In some projects we have even used both Zend and Drupal together.

Actually tech decision depends on many factors like budget, cost, clients internal policies and application requirements. Zend is a framework, while Drupal is also a CMS with good framework for a foundation of good application. Different modules also supports us. As I have mentioned in my estimation email, we are also going to get benefits of our earlier work on similar things.

In your application structure, Drupal is perfect choice. Having said that I would like state that your project is also doable in Zend, but in that case we will loose the benefits of ready made modules and our earlier work.

Again, I will repeat ,we can handle both, but economically and time wise Drupal is best choice for you if you do not have issues with its GNU  GPL license.

 

I have done extensive work in both Zend framework development as well as Drupal development. Drupal and Zend both are feature rich and secures platforms if you can develop and deploy your apps with a proper planning. If you feel that an expert with good experience in both Zend and Drupal development may help you in your decision between Zend and Drupal. Please feel free to contact me , you can also chat with me if I am online.

PHP Functions to work with PHP Arrays

This posts was written in year 2006 on 20th May. In one of my server crash, I lost my posts, Today I got it recovered from Archive.org, and representing it again.

 

Today, I am going to write about array PHP functions, these functions allow you to interact with and manipulate arrays in various ways.
Arrays are essential for storing, managing, and operating on sets of variables.

What are Arrays?

This is very easy to tell but sometime it is really difficult to understand the dynamics of arrays, after functions, arrays are one of the greatest mechanism of programming to solve the problem of data maintenance and presentation.

Arrays are collections of data in a particular way.

To know more about array in programming visit wikipedia page or you can visit php array page to know specifically about PHP arrays.

PHP has many functions to work with arrays, You can view the list and short explanation of their working at http://www.php.net/arrays

In this article I have listed only some very important functions, but it does not mean that other functions are not important , every function has its importance in the context of that’s functions requirement.

Some Array Functions are :-

array_chunk()
This function split an array into chunks, it is useful to divide a large array into smaller once. You may also have an array with less values at the end. You get the arrays as members of a multidimensional array indexed with numbers starting from zero.

array_combine()
Creates an array by using one array for keys and another for its values
Returns FALSE if the number of elements for each array isn’t equal or if the arrays are empty.

array_diff()
This function returns an array containing all the values of array1 that are not present in any of the other arguments. Note that keys are preserved.

array_flip()
Exchanges all keys with their associated values in an array This function returns an array in flip order, i.e. keys from trans become values and values from trans become keys.

array_merge()
array_merge() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.

array_pop()
This is one of shortest and easy but yet very useful function, this function return the last element of array,. A simple use is to get the extension of any file while using it with explode function.

$ext=array_pop(explode(“.”,”this.is.file.ext”));

array_rand()
Pick one or more random entries out of an array
If you are using random function of php then calling the index as per that value, you can use this function to get random results. One of neat function of PHP.

array_reverse()
Just reverse the over of array elements.

array_search()
Searches the array for a given value and returns the corresponding key if successful

array_slice()
Extract a slice of the array

array_unique()
Removes duplicate values from an array

array_walk()
Apply a user function to every member of an array

extract
I have used this function almost in my every application, using this function you can even simulate the register_globals=On effect in the PHP version where they are Off (They should be off in any ideal PHP installation.)

in_array()
Checks if a value exists in an array

natsort()
Sort an array using a “natural order” algorithm

shuffle()
Shuffle an array

Some very useful functions are listed at http://www.zend.com/codex.php?CID=281. These functions are not in built in the PHP , but they really save the time in need.

How to optimize all databases and tabels on mysql server?

Optimization of database tables in mysql is a process which has to be carried out regularly to make your database in good health.

According to mysql manual,

OPTIMIZE TABLE should be used if you have deleted a large part of a table or if you have made many changes to a table with variable-length rows (tables that have VARCHAR, VARBINARY, BLOB, or TEXT columns). Deleted rows are maintained in a linked list and subsequent INSERT operations reuse old row positions. You can use OPTIMIZE TABLE to reclaim the unused space and to defragment the data file. After extensive changes to a table, this statement may also improve performance of statements that use the table, sometimes significantly.

In phpmyadmin you can see data similar to following screen if your database tables are not optimized. Entries in Overhead column indicates size of data space which can be reclaimed after optimization.

A major challenge comes in optimization when you have many databasesm thus many tables on my mysql server. It is hard to do optimization manually for each and every table. So we have created this script which can optimize each and every table of each database on your mysql server. You can run this script as your cron script also so you can do your optimization activities automatically. We have also executed repair statement which will repair any table error.


$con=mysql_connect(DATABASE_HOST,DATABASE_USER,DATABASE_PWD);
$db_list = mysql_list_dbs($con); $dbtoProcess=array();
while ($row = mysql_fetch_object($db_list))
{
$dbtoProcess[]=$row->Database;
}

foreach ($dbtoProcess as $dbname) {
$db=mysql_select_db($dbname);
$sql = "SHOW TABLES FROM `$dbname`";
$result = mysql_query($sql);

$AllTablesinDB=array();
while ($row = mysql_fetch_row($result)) {
$AllTablesinDB=array_merge($AllTablesinDB,$row);
}

foreach($AllTablesinDB as $value)
{
mysql_query("optimize table $value");
mysql_query("repair table $value");
//print $value ." has been optimized and repaired";

}
}

Execution of this script may take some time depending on the size of databases and tables.

Using PHP and Java in the Same App with PHP/Java Bridge

In this article you will learn how to install and configure the PHP/Java Bridge and how to use Java classes in PHP scripts in a demo application. To use the PHP/Java bridge, you should have knowledge of Java SE and the PHP5 core, as well as how they interact.

PHP 4 supported an extension for combining PHP with Java, but to combine PHP with Java in PHP 5  you should install the PHP/Java Bridge, which the website describes as:”… an implementation of a streaming, XML-based network protocol, which can be used to connect a native script engine, for example PHP, Scheme or Python, with a Java virtual machine.”

Read complete article at PHP section of developer.com written by Octavia Andreea Anghel.

 

Integrating Zend Framework with Drupal and WordPress

Zend Framework is not only a framework but a robust library for many kind of operations and services. While working with Drupal or WordPress sometime we found that a good library for one particular operation is already available in Zend Framework.

You can easily use Zend Framework library in your projects with bothering about its app framework and MVC structure. Drupal and WordPress both have mechanism to use Zend framework in them without doing any major work.

Drupa module for Zend Framework

Its very easy to setup and use. You can start using Zend Framework in your Drupal modules within few minutes.
Installation and usage instructions are available on Module’s page.

http://drupal.org/project/zend

This module is available for version 6 as well as 7 of Drupal.

WordPress plugin for Zend Framework

http://wordpress.org/extend/plugins/zend-framework

This module also provide embedded Zend framework library and easy to install and setup.

Plugin’s official setup instructions need one clarification (As I am writing this).

On page

http://wordpress.org/extend/plugins/zend-framework/installation/

Following instruction has been mentioned.

1. Upload plugin-name.php to the /wp-content/plugins/ directory

I think writer forgot to change the instruction template, this can be read at

1. Upload zend-framework folder to the /wp-content/plugins/ directory

One more plugin is also available for WordPress at

http://wordpress.org/extend/plugins/wp-zff-zend-framework-full

This module has instructions which are more detailed and precise to be used.

Let�s plug the power of Zend Framework library to these wonderful CMSs and enjoy the benefits.

PHP Functions to work with PHP functions

In this article, I am going to write about the functions using which you can get the information about php functions.

For a full list of PHP functions you can visit http://www.zend.com/phpfunc/

Using these functions you can query the stats/status of your functions, these functions are very useful in dynamic application creation.

For example, using func_get_arg and func_num_args functions you can simulate the function overloading in PHP.

Read a good example for http://www.dubi.org/php-function-overloading

Functions I will write in this article are :-

get_defined_functions();

You want to how many functions are in your installation of PHP, just call this function, it will return an array of all php functions you can call. For the convince it return an multidimensional array, so you can access both internal and user defined functions separately.

func_get_arg()

Returns the argument which is at the arg_num’th offset into a user-defined function’s argument list. Function arguments are counted starting from zero. func_get_arg() will generate a warning if called from outside of a function definition. This function cannot be used directly as a function parameter. Instead, its result may be assigned to a variable, which can then be passed to the function.
If arg_num is greater than the number of arguments actually passed, a warning will be generated and func_get_arg() will return FALSE.
As this function depends on the current scope to determine parameter details, it cannot be used as a function parameter. If you must pass this value, assign the results to a variable, and pass the variable.

func_get_args()

Returns an array in which each element is a copy of the corresponding member of the current user-defined function’s argument list. func_get_args() will generate a warning if called from outside of a function definition. This function cannot be used directly as a function parameter. Instead, its result may be assigned to a variable, which can then be passed to the function.
This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.
As this function depends on the current scope to determine parameter details, it cannot be used as a function parameter. If you must pass this value, assign the results to a variable, and pass the variable.

func_num_args() Returns the number of arguments passed into the current user-defined function. func_num_args() will generate a warning if called from outside of a user-defined function. This function cannot be used directly as a function parameter. Instead, its result may be assigned to a variable, which can then be passed to the function.
As func_get_arg() this function also can not be passed as argument to another function.

function_exists()

Checks the list of defined functions, both built-in (internal) and user-defined, for function_name. Returns TRUE on success or FALSE on failure.

create_function()

Creates an anonymous function from the parameters passed, and returns a unique name for it. Usually the args will be passed as a single quote delimited string, and this is also recommended for the code. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. $avar.

This is one of very useful function to create dynamic application, using this function you can create the function at run time and then use them as per your requirements.

call_user_func()

Call a user defined function given by the function parameter.
People are divided on the use of this function, some thinks that it is not needed at all when we can run the function on the variable itself.
Like use of this function is

function test($value)
{
print "This is $value";
}

call_user_func("test","test value");

some people prefer using variable function like this :-

$funcname="test";
$funcname("test");

This is also a call_usr_func_array function.

is_callable()

If you are going to use a a variable function like previous example, you may need to verify if a function already present and callable? using this function you can do that.
This function Verify that the contents of a variable can be called as a function. This can check that a simple variable contains the name of a valid function, or that an array contains a properly encoded object and function name.
The var parameter can be either the name of a function stored in a string variable, or an object and the name of a method within the object, like this:

array($SomeObject, 'MethodName')

In some way it is similar to function_exisits function but it does more that that if you just want to check the syntax then you can pass a second argument as True, in that case it only verifies that var might be a function or method. It will only reject simple variables that are not strings, or an array that does not have a valid structure to be used as a callback. The valid ones are supposed to have only 2 entries, the first of which is an object or a string, and the second a string.

PHP is a functional language and you can almost do anything with these functions.

Use Exit after redirecting user via header function

Some weeks ago I got an old PHP application to work with. I was asked to look for the potential problems and bottlenecks in the application. So I decide to use APD as a profiler for the application, after installing the APD on that server. I enabled profiler on one of the reportedly slow page.

That page was meant to be displayed and executed only if user is logged in and session variables are set. If we don’t found user session then user was being redirected to Login page of the application.

I called that page directly in the browser and got the login screen. It was perfectly acceptable behavior.

BUT when I run the profiler to get the information about the execution of page I was surprised to see that almost all functions which were only meant to be executed for logged in users were being called and they were taking the system resources.

Just to confirm I refresh the page in browser many time (without login), and each time I got same profile information for page.

Then I run the test using Apache benchmark (ab) and while test was in running I decide to see the process list of mysql database, again I see that heavy queries were being fired on the database. (But this time I was not surprised, as it was expected and I did just to confirm and take the screen shot so I can show that to the owner of the application.)

Now I decide to check the reason behind this, so I opened that page in my Zend Studio, and yes I got the reason …

Application was redirecting the user to login page if user is not logged in using header function via location define mechanism Like

  header("location: login.php");

And they were not using exit after that. I just add the exit(); after that header function call and problem was fixed.

header("location: login.php");
exit();

Just an improper use of header was the reason behind unnecessary load on the web server as well as on database server.

Note : If you do use the location setting of the header to redirect to another page, do not forget to use “exit;” to prevent further execution of script code.

Using SQL abstraction and CRUD factory classes is a good practice?

This question again struck me today, somebody just throw a simple question about EXPLAIN statement in MySQL and in hast I relate that to DESCRIBE. When that person cut the line of phone, I suddenly realize my mistake.

I am working with PHP and MySQL since last seven years then why this happen to me? This is because I am not using MySQL frequently, although it is the integral part of almost every application I am working on. I am fairly away from MySQL queries because I am using my factory classes or framework like cakephp which does not require me to write the SQL queries. Almost all of my operations on database are covered within my CRUD classes. Even complex select or updates are possible using simple search objects in my factory classes or framework I am using.

BUT this practice has caused a deficiency in my knowledge of MySQL statements. This situation is really horrible sometime. Do I need to stop using my factory classe practice and abstraction. I normally prefer abstraction and factory classes because I want to make my code portable to other databases also.

I am really a in fix What should I do?
BUT again another question struck me What is more important? My knowledge of MySQL statements or fast and portable execution of projects. When we got the higher level, we certainly miss the lower level details of applications.

So I will stick to my factory classes, because I know I may struggle with some academic questions about MySQL for the time being but at least I can do the stuff with just one reference to MySQL manual. Above all I may face problem in simple MySQL statements but I am good at high level things like replication and performance tuning at server level.

What you say is it a good decision?

PHP4 and PHP5 version conflicts and why we should stop using PHP 4

PHP 5 is in the market since many years, but it still has to capture the market.

Why? Is it not efficient version of PHP language?

What are main reasons behind slow-adoption of PHP version 5.

I am compiling a list of reasons; you can also send me the reason why you have moved to PHP5 or why you are not able to do that?

I will write about that list in my coming articles.