Category Archives: synapseindia reviews

customer reviews online for synapseindia

SynapseIndia Php Development-The Case Against Drupal Base Themes

When it comes to Drupal base themes, it seems the conversation is often limited to which one you should choose, rather than discussing whether you should be using one at all.

As someone who has spent a lot of time extolling the virtues of various base themes, I thought I’d share the other side of the argument and ask if we should be using contributed base themes – those available from drupal.org – in our projects. For the purposes of this post, the distinction between contributed base themes and one you might build yourself is important as we’ll see in a moment.

This discussion is really part of a larger debate that front-end developers are having about CSS and grid frameworks in general (see here and here), but it seems particularly relevant when discussing Drupal base themes because all of the issues are magnified due to added complexity.

Why We Use Base Themes

Why do so many of us use base themes? The easy answer is that they can save us time and potentially make us more efficient. Sometimes they can also act as common ground for development teams. But I think a more complete answer is that they act as a useful crutch, particularly when first learning Drupal theming or responsive design.

At some point we all had to build our first Drupal site or our first responsive site – probably under deadline – and we looked to a base theme or framework for help. It allowed us to get the job done on time and within budget, but perhaps without fully understanding everything that was going on under the hood.

Over time we probably learned most of the base theme and developed a deeper understanding of responsive design, but the framework eventually became a comfortable place. We stuck with it, happily soldiering on until one day…

When the Shortcut Becomes the Long Way

If you’ve been working with base themes for a while, the moment has certainly come when you have found yourself fighting with it. By design, base themes and other frameworks are opinionated – they make decisions about how to solve certain problems. Most of the time this is a good thing. It can help you accomplish things more quickly. Until it doesn’t, and then your base theme is actually slowing you down and causing problems.

Part of the reason why this happens is that the developer doesn’t have full mastery of the base theme –  or underlying concepts  – and therefore doesn’t know why something is happening. This is bound to happen with base themes like Omega and Zen that are complex and have a very granular file structure, lots of hooks, etc. It can take some effort to track issues down.

Other times it’s not mastery as much as the choices being made by the base theme don’t match up with the project at hand. You find yourself at cross purposes with the base theme, possibly even trying to sort out incompatibilities between the base theme and a module you want to use.

And all the hacks you add to sort things out? More kilobytes that have to be downloaded by a user on a mobile device.

Fast Sites Win the Day

This leads us to another reason you might not want to use a base theme – it will probably slow down your site vs a theme that is tailored for a specific project. The case has been definitively made that faster sites are more successful sites (see here and here). In most cases, base themes are going to include a lot of stuff that you are not going to need on a given project. The ‘extra’ stuff is bloat that will end up slowing your site down.

This isn’t a slam on base themes. Most of them are akin to a Swiss army knife. They have things in them that help accomodate a lot of different scenarios – they’re flexible. This can be a big help if you’re a beginner, but what if you’re a seasoned front-end developer tasked with building a high performance site?

In that case, maybe a base theme isn’t the way to go.

The Role for Base Themes

Some will sing the praises of Mothership or Tao or their favorite lean base theme of choice, insisting it solves all of the issues I’ve mentioned. I certainly have no quarrel with using those base themes on projects if you’ve mastered them and find them useful. It can also be helpful to employ Zen or Omega. It really depends on the specific project. This isn’t a post bashing base themes.

My own thinking on the topic, however, has shifted. I’ve decided to move away from base themes whenever possible. My decision stems from wanting lean code that helps me build fast, mobile-first sites. It also allows me to understand exactly what is happening with the code because I’m the one who wrote it. Ultimately, I think this practice makes me better at my job as a front-end developer, and importantly, I’m also delivering a better product to my clients. I came to this place after spending so much time hacking apart base themes that they were no longer recognizable. It made more sense to just chuck them entirely and start fresh.

Of course, I haven’t thrown efficiency considerations aside. I have my own starter theme to make my work easier, and this is what I would advise others who are considering a base theme to do as well. Create your own bag of tricks. If there ends up being things in it that don’t fit a particular project, you’ll know exactly where they are so that you can easily discard them.

One last tangential thought on this topic – a fantastic development for Drupal 8 would be for core to add no CSS whatsoever, minimal markup and then let themes in contrib add commonly requested bells and whistles. This is a philosophical approach that would be hugely positive for Drupal as a mobile-first approach takes hold as the standard for front-end development.

Advertisements

SynapseIndia Smarty PHP Template Engine: Building PHP Apps in a Flash Development

Smarty is a template engine for PHP whose main goal is to facilitate a very useful way to separate the business logic from the presentation logic. This article introduces Smarty and demonstrates how to install the template, create an application from scratch and interact with a database.

Installing the Smarty Template Engine

The Smarty template engine can be downloaded from the official website. At this site you will also find complete documentation that will help you to learn more about working with Smarty templates.

To install and use Smarty you should go through the following steps:

  1. Unzip the Smarty archive to the proper directory. I put the Smarty library into theD:/Apache2.2/htdocs/php/ path. You should see the structure below in the Smarty directory.

    Click here for larger image

    Figure 1. The Structure of Smarty/libs Folder
  2. Now, to test if Smarty is correctly installed, you should put the code below into the index.phpscript. As you can see from the listing below, before checking if all the required working folders can be accessed (using the testInstall() method) , you should create a new Smarty variable:
    <?php
    
    //Put full path to Smarty.class.php
    require('D:/Apache2.2/htdocs/php/Smarty/libs/Smarty.class.php');
    
    //Create new variable $smarty from the class Smarty
    $smarty = new Smarty();
    
    //Verifies that all required working folders of the Smarty installation can //be accessed
    $smarty->testInstall();
    
    ?>
  3. To see the output of the test, write http://localhost/php/Smarty/demo/index.php into the browser. You should get something like this:
    Smarty Installation test...
    Testing template directory...
    .\templates\ is OK.
    Testing compile directory...
    .\templates_c\ is OK.
    Testing plugins directory...
    D:\Apache2.2\htdocs\php\Smarty\libs\plugins\ is OK.
    Testing cache directory...
    .\cache\ is OK.
    Testing configs directory...
    .\configs\ is OK.
    Tests complete.

Creating a New Simple Smarty Application

In this section you will see how to create your own “Hello World” application. To do that, you should first create a new folder (I named it Smarty_example) in theD:/Apache2.2/htdocs/php/ directory, set the template directory for use with different templates (as you will see below in the index.php script), assign a variable (in this case,name) and then compile and display the template file, index.tpl.

<?php

//Put the full path to Smarty.class.php
require('D:/Apache2.2/htdocs/php/Smarty/libs/Smarty.class.php');

//Create new variable $smarty from the class Smarty
$smarty = new Smarty();

//Set the template directory used for different templates
$smarty->setTemplateDir('/ Smarty_example /templates');
//Set the compile directory 
$smarty->setCompileDir('/ Smarty_example /templates_c');
//Set the cache directory
$smarty->setCacheDir('/ Smarty_example /cache');
//Set the configs directory
$smarty->setConfigDir('/ Smarty_example /configs');

//Set the name variable variables
$smarty->assign('name', 'WORLD');

//Compile and display output of the template file
$smarty->display('index.tpl');

?>

The template file, index.tpl, looks like this:

<html>
  <head>
    <title>Smarty</title>
  </head>
  <body>
    Hello, {$name}!
  </body>
</html>

The output of the “Hello World” application is:



Click here for larger image

Figure 2. The Output of the First Simple Application “Hello World”

SynapseIndia PHP OOP Class for count down to any date or event Development

Calendars/Dates    GNU General Public License

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
/**************************************************************
# TITLE : Object Oriented Approach to countdown to any particular date or event           *
# Same procedural snipped is posted in Help Manual ---> date()
# If you compare both snippets, It would be easy to understand PHP-OOPs!
***************************************************************/
//Any of following input can be retrieved by GET OR POST.
//Input is set for New Year event.
$year = '2009';
$month= '01';
$day = '01';
$hour = '00';
$minute = '00';
$second = '00';
$date = array($hour,$minute,$second,$month,$day,$year);
//Defining class bt keyword class
class DateCountDown {
//Class member definition - Easy to remember class members
var $year = "";
var $month= "";
var $day = "";
var $hour = "";
var $minute = "";
var $second = "";
var $date = "";
var $dl = "";
var $hl = "";
var $ml = "";
var $sl = "";
var $return = "";
//Countdown to particular Function
function countdown(){
  global $return;
  global $countdown_date;
  global $date;
  list ($hour, $minute, $second, $month, $day, $year)= $date;
  $countdown_date = mktime($hour, $minute, $second, $month, $day, $year);
  $today = time();
  $diff = $countdown_date - $today;
  if ($diff < 0)$diff = 0;
  $dl = floor($diff/60/60/24);
  $hl = floor(($diff - $dl*60*60*24)/60/60);
  $ml = floor(($diff - $dl*60*60*24 - $hl*60*60)/60);
  $sl = floor(($diff - $dl*60*60*24 - $hl*60*60 - $ml*60));
// OUTPUT
$return = array($dl, $hl, $ml, $sl);
return ($return);
}
}
//Making New Object for the class CountDownDate
$date_obj = new DateCountDown($date);
//Function (Method) call by an object to function countdown
$date_obj -> countdown();
//Making varialbes $dl => Days Left, $hl => Hours Left and so on from $return array
list($dl,$hl,$ml,$sl) = $return;
//Browser Output
echo "Today's date ".date("F j, Y, g:i:s A")."<br/>";
echo "Countdown date ".date("F j, Y, g:i:s A",$countdown_date)."<br/>";
echo "\n<br>";
echo "Countdown ".$dl." days ".$hl." hours ".$ml." minutes ".$sl." seconds left"."\n<br>";
/*
Above snippet produces following output:
Today's date February 11, 2008, XX:XX:XX PM
Countdown date January 1, 2009, 12:00:00 AM
Countdown 324 days XX hours XX minutes XX seconds left
*/
?>

SynapseIndia Reading RSS feeds in PHP Development : Part 1

I’m sure everyone who calls themselves a PHP coder has heard of RSS. I have to include the disclaimer, as I’m always surprised how little penetration concepts I take for granted have in the rest of the world. Recently, a colleague in the music industry started a blog. I saw there were no RSS feeds available, and asked him when they’d be ready. He had no clue what I was talking about. I shouldn’t really have been surprised. Nevertheless, RSS feeds are starting to take the world by storm.
Recently I was looking for an RSS aggregator. I was having surprising difficulty finding one that did exactly what I wanted. Being quite impatient, especially when I’d spent more time looking than it would have taken me to write one had I started immediately, I began seriously considering writing my own. This month, I show you how to create a basic RSS reader yourself.
What is RSS?
I’m not interested in getting into the debate as to whether RSS stands for Really Simple Syndication, Rich Site Summary, RDF Site Summary, or anything else. Nor which of the RSS versions are ‘better’. This article is not going to investigate the differences between the various RSS versions either. If we’re going to be using PHP to read RSS, we need to rather know some of the basic technical details of what an RSS feed comprises of.
RSS is most simply understood as an implementation of XML. It contains (roughly, as versions differ!) the following elements (full specifications can be found at http://web.resource.org/rss/1.0/spec and http://blogs.law.harvard.edu/tech/rss:

* <title>, the feed title, or the name of the channel.
* <description>, a short piece of text describing the feed.
* <link>, the URL of the corresponding web page.
* <language>, the language used for the content (for more details see RFC1766, Tags for the Identification of Languages.
* <lastBuildDate>, the date and time the feed was updated.
* <pubDate>, the date and time the content was published.
* <copyright>, any copyright information.
* <generator>, the software used to generate the RSS.
* <docs>, a URL pointing to documentation for the format used in the RSS file (usually one of the specification links above).
* <ttl>, time to live, or how long the feed can be cached, in minutes.
* <image> An image related to the RSS feed. This in turn contains up to 6 sub-elements, the first three being mandatory:
o <title> Same function on the channel’s title, and usually contains the same string.
o <url> Image URL.
o <link> Same function on the channel’s image, and usually contains the same string.
o <width> In pixels, maximum of 144, default of 88.
o <height> In pixels, maximum of 400, default of 31.
o <description> The HTML title attribute.
* <rating> The PICS rating, originally designed for access control for parents and teachers. See the W3C specification.
* <cloud> Specifies a cloud web service which allows notification of updates.
* <textInput> Used to specify a text input box, which isn’t usually that useful, and we don’t look at here.
* <skipHours> This tells well-behaved aggregators when not to read the feed, reducing unecessary reads when nothing has changed. It consists of up to 24 <hour> elements, each containing a number from 0 to 23, representing an hour to be skipped.
* <skipDays> Similar to <skipHours>, this consists of <day> sub-elements, each listing a day to be skipped (written in full, such as Saturday).
* <webmaster> If you enjoy harvesting spam, you may also want to put the email address of the person responsible for technical issues.
* <managingEditor> Another spam harvester, this time the email of the editor responsible for the content.
* <item> Most importantly, it also contains a number of items, which are usually the articles, stories or posts you’re interested in reading. It contains a number of sub-elements, all of which are optional, although one of either title or description must be present.
o <title> Usually the article headline.
o <description> Usually a short blurb, although it can contain the entire contents.
o <link> URL to the item.
o <author> More potential spam gathering, this one is for the email address of the item’s author
o <category> String identifying the category
o <comments> URL for item comments
o <enclosure> Used for attached video or audio files. It has 3 attributes – URL, length (in bytes) and type.
o <guid> A unique identifier (Globally Unique Identifier). Usually a URL. Has an attribute, is PermaLink, which tells the reader whether the guid is a URL to the item (it defaults to true).
o <pubDate> Date and time when the item was published
o <source> Text string of the source, it also has a required attribute, url, which links to the source’s XMLization

After all that’s let’s look at a sample, loosely based on that of the PHPBuilder website. For simplicity I’ve included just two items. It’s in RSS 0.91 format.

<?xml version=”1.0″?>
<rss version=”0.91″>
<channel>
<pubDate>Thu, 29 Sep 2006 15:16:13 GMT</pubDate>
<description>Newest Articles and How-To’s on PHPBuilder.com</description>
<link>http://phpbuilder.com</link&gt;
<title>PHPBuilder.com New Articles</title>
<webMaster>staff@phpbuilder.com</webMaster>
<language>en-us</language>  <item>
<title>In Case You Missed It…The Week of September 26, 2006</title>
<link>http://www.phpbuilder.com/columns/weeklyroundup20060926.php3</link&gt;
<description>This week Elizabeth brings us news of an upcoming free
webcast called Design Patterns in PHP, the schedule for the Fall Zend conference,
security alerts for Moveable Type and phpBB, the release of Zend Platform 2,
XAMPP for Linux, the latest PEAR/PECL releases and much more!
</description>  </item>  <item>
<title>In Case You Missed It…The Week of September 19, 2006</title>
<link>http://www.phpbuilder.com/columns/weeklyroundup20060919.php3</link&gt;
<description>This week Elizabeth brings us news of the release of PEAR 1.4,
Zend Studio 5 Beta, a security vulnerability with PHP-Nuke, the release of a
SimpleTest plugin for PHPEclipse, a patch for phpMyAdmin, the latest PEAR/PECL
releases and much, much more!</description>
</item>
</channel>
</rss>

SynapseIndia Implementing User Defined Interfaces in PHP 5 Development

Starting with PHP 5 the object model was rewritten to add features and bring PHP in line with languages such as Java and Visual Basic .NET. In this article I’ll discuss interfaces, which is among the most important features in PHP 5. Other important features includevisibility, abstract and final classes, methods and additional magic methods. You will learn how to define your own interfaces and how to work with them using different object model mechanisms.

 

While PHP 5 also comes with a set of predefined interfaces that may help you in understanding and working with interfaces their illustration is beyond the scope of this article. For your reference some of these predefined interfaces are Traversable, Iterator,IteratorAggregate, ArrayAccess, Serializable and Closure.

A PHP interface defines methods that are used define a behavior for an object. Follow these rules when working with PHP interfaces:

 

* Interfaces do not implement methods.

* Interfaces are not part of a hierarchy of classes.

* Interfaces are not similar to abstract classes.

* A class can implement any number of interfaces.

* The same interface can be implemented by several classes.

* A class that implements an interface must implement the methods defined in the interface.

* A class that implements an interface may not implement its methods if the interface is declared abstract.

* When a class implements an interface automatically the class inherits the constants declared in the interface.

 

In general this is how you declare an interface:

1
2
3
4
5
interface int_name [extends      
                            superint1_name, superint2_name,...]
                         {
                         //int_name interface body
                         }

 

Where:

 

* interfaces – the key word

* int_name – the name chosen by the programmer interface

* extends – the key word

* superint1_name, superint2_name – an interface can extend any number of superinterfaces Interfaces that are extended should be separated by a comma.

* interface body – where the programmer declares constants (if any) and defines the methods to be implemented by any class that will extend the interface

 

Remarks:

 

* All methods declared in an interface must be public.

* The class implementing the interface must use the exact same method signatures as are defined in the interface.

* A class cannot implement two interfaces that share function names.

* Interfaces may have constants. Interface constants work exactly like class constants except they cannot be overridden by a class/interface that inherits it.

* Before creating an interface you should know where you will implement it in different classes. Changing the interface method signature after it has been implemented (implementation of the methods defined in the interface) requires modification of all classes that implement the interface.

* When a class implements an interface, it must provide an explicit implementation for each method declared within the interface itself.

 

Creating a simple interface example

Below are a few examples of user defined interfaces. The first example creates an interface that is implemented by two classes to randomize a string. Notice that the MyStringInterface interface contains a public function, getString, containing two arguments representing the interval values between which the randomized string should be found.

Listing: MyStringInterface.php

1
2
3
4
5
6
<?php
interface MyStringInterface
{
    public function getString($var1, $var2);  
}
?>

 

The MyStringClass class below implements the MyStringInterface interface from above and uses the getString function to randomize a string using the PHP method rand. Notice that the class that implements the interface must use the exact same method signature as is defined in the interface.

Listing: MyStringClass.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
include_once('MyStringInterface.php');
class StringRandom implements MyStringInterface
{
      public function getString($var1, $var2)
    {
        $string = rand($var1, $var2);
        return $string;
    }                                                   
}
                                                            
?>

Listing: TestMyRandomString.php

1
2
3
4
5
6
7
8
9
10
<?php
include_once('MyStringClass.php');
echo("Randomized string");
$intnr = new StringRandom();
$n= $intnr->getString(10e16, 10e20).'';
echo base_convert($n, 10, 36);
?>

 

The output of TestMyRandomString.php script is:

 

Implementing User Defined Interfaces in PHP 5
Figure 1. Randomizing a String Using a Simple Interface Example

Extend Interfaces

The next example shows how to extend an interface. To extend an interface you use the extend keyword. The extension mechanism is shown below in the MyNumberRandomInterface interface example and extends the MyRandomInterface. When you implement the MyNumberRandomInterface interface you also have to provide a behavior for the function defined to the extended interface. You can see an example in the IntAndStringRandom.php listing below, which implements the MyNumberRandomInterface interface. You can test the extension interface mechanism by using the testMyRandom.php PHP script. The script creates an instance of IntandStringRandom class and outputs the randomized string and number based on each corresponding method declared to that class.

Listing: MyRandomInterface.php

1
2
3
4
5
6
<?php
interface MyRandomInterface
{
    public function getString($var1, $var2);  
}
?>

Listing: MyNumberRandomInterface.php

1
2
3
4
5
6
7
8
9
<?php
include_once('MyRandomInterface.php');
interface MyNumberRandomInterface extends MyRandomInterface
{
    public function getNumber();  
}
?>

Listing: IntAndStringRandom.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
include_once('MyNumberRandomInterface.php');
class IntAndStringRandom implements MyNumberRandomInterface
{
  public function getString($var1, $var2)
    {
        $string = rand($var1, $var2);
        return $string;
    }   
               
  public function getNumber(){
    $number = rand(100,500);
     return $number;
    }                               
}
?>

Listing: TestMyRandom.php

1
2
3
4
5
6
7
8
9
10
11
12
<?php
include_once('IntAndStringRandom.php');
$test = new IntAndStringRandom();
echo("String");
echo $test->getString(10e16, 10e20).'';    
echo("Integer number");
echo $test->getNumber(0,100).'';
?>

 

The output of extended interfaces is shown below in Figure 2.

 


user defined interfaces in php 5
Figure 2. Randomizing a String and an Int Using the Interface Extend Mechanism

Multiple extension interfaces

The examples below show, as the name suggests, multiple extension interfaces. This can be seen in the MyCharRandomInterface interface that extends the MyRandomInterface and MyNumberRandomInterface. Again, when you implement the MyStringRandomInterface interface you have to provide a behavior for each function defined in each extended interfaces. You can see that behavior in the IntCharAndStringRandom.php listing, which implements the MyCharRandomInterface interface. And again you can test the multiple extension interfaces mechanism with the testMyRandom.php PHP script. In this case the script creates an instance of IntCharAndStringRandom class and outputs the randomized string, number and char based on the corresponding methods declared for that class:

Listing: MyRandomInterface.php

1
2
3
4
5
6
<?php
interface MyRandomInterface
{
    public function getString($var1, $var2);  
}
?>

Listing: MyNumberRandomInterface.php

1
2
3
4
5
6
7
<?php
interface MyNumberRandomInterface
{
    public function getNumber();  
}
?>

Listing: MyCharRandomInterface.php

1
2
3
4
5
6
7
8
9
10
<?php
include_once('MyRandomInterface.php');
include_once('MyNumberRandomInterface.php');
interface MyCharRandomInterface extends MyRandomInterface, MyNumberRandomInterface
{
    public function getChar();  
}
?>

Listing: IntCharAndStringRandom.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
include_once('MyCharRandomInterface.php');
class IntCharAndStringRandom implements MyCharRandomInterface
{   
  public function getString($var1, $var2)
    {
        $string = rand($var1, $var2);
        return $string;
    }   
  public function getNumber()
    {
        $number = rand(100,4000);
        return $number;
    }                  
  public function getChar(){
    $chars = 'bcdfghjklmnprstvwxzaeiou';
     $ch = $chars[mt_rand(0, 18)];
     return $ch;
    }  
}                          
?>

Listing: TestMyRandom.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
include_once('IntCharAndStringRandom.php');
$test = new IntCharAndStringRandom();
echo("String");
echo $test->getString(10e16, 10e20).'';    
echo("Integer number");
echo $test->getNumber(0,100).'';  
echo("Character");
echo $test->getChar().'';
?>

 

The output of multiple extension interfaces is shown below in Figure 3.

 


user defined interface in php 5

Figure 3. Randomizing a String and an Int Using the Interface Extend Mechanism

Overloading

Overloading in PHP means to dynamically “create” properties and methods. Overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope. The next application shows how to overload the getNumber method using different number of arguments. The _call() PHP method takes as its first argument the getNumber() method, and as its second argument the number of arguments used in the getNumber() method. In this example you will use two argument sets in the TestMyRandom.php script that call the getNumber() method.

 

Note that all overloading methods must be defined as public.

Listing: MyRandomInterface.php

1
2
3
4
5
6
<?php
interface MyRandomInterface
{
    function __call($method, $arguments);
}
?>

Listing: MyRandomClass.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
include_once('MyRandomInterface.php');
class IntRandom implements MyRandomInterface
{
  
    function __call($method, $arguments) {
            if($method == "getNumber" && count($arguments) == 0) {
               return rand();
        }
            if($method == "getNumber" && count($arguments) == 2) {
               return rand($arguments[0],$arguments[1]);
        }
        return -1;
    }                                                  
}
class FloatRandom implements MyRandomInterface
{
  function __call($method, $arguments) {
            if($method == "getNumber" && count($arguments) == 0) {
           return mt_rand()/100;
        }
            if($method == "getNumber" && count($arguments) == 2) {
           return mt_rand($arguments[0],$arguments[1])/100;
        }
        return -1;
    }
 
}
?>

Listing: TestMyRandom.php

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
include_once('MyRandomClass.php');
echo("Integer number");
$intnr = new IntRandom();
echo $intnr->getNumber(0,100).'';
echo("Float number");
$floatnr = new FloatRandom();
echo $floatnr->getNumber(1,1000);
?>

 

The output of overloading getNumber() method is shown below in Figure 4.


user defined interface php 5

Figure 4. Rand an Int and a Float Using the Overloading Method Mechanism

Default and Override

The last example shows how to override the getNumber() method using the MyRandomClass. The MyRandomClass contains the IntRandom and FloatRandom classes that extend the IntDefaultRandom and FloatDefaultRandom default classes.

Listing: MyRandomInterface.php

1
2
3
4
5
6
<?php
interface MyRandomInterface
{
    public function getNumber($var1, $var2);  
}
?>

Listing: MyDefaultRandomClass.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
include_once('MyRandomInterface.php');
class IntDefaultRandom implements MyRandomInterface
{
  public function getNumber($var1, $var2)
    {
        $number = rand($var1, $var2);
        return $number;
    }                                                   
}
class FloatDefaultRandom implements MyRandomInterface
{
   
  public function getNumber($var1, $var2)
    {
        $number = mt_rand($var1, $var2)/100;
        return $number;
    }
}
?>

Listing: MyRandomClass.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
include_once('MyDefaultRandomClass.php');
class IntRandom extends IntDefaultRandom
  {
  
  }
class FloatRandom extends FloatDefaultRandom
  {      
  }
?>

Listing: TestMyRandom.php

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
include_once('MyRandomClass.php');
echo("Integer number");
$intnr = new IntRandom();
echo $intnr->getNumber(0,100).'';
echo("Float number");
$floatnr = new FloatRandom();
echo $floatnr->getNumber(1,1000);
?>

 

The output that results from using the default and overriding getNumber() methods is shown below in Figure 5.


user defined interface php 5
Click here for larger image

Figure 5. Randomize an Int and a Float Using the Method Override Mechanism

SynapseIndia Using CodeIgniter Layout Pattern Development

CodeIgniter is great framework by its simplicity. But when I moved from CakePHP, I really missed layout pattern. CodeIgniter documentations offer this way to include non-changing site header and footer.

 

1
2
3
4
5
<?php
$this->load->view('header');
$this->load->view('template');
$this->load->view('footer');
?>

 

For sure it isn’t flexible and does not show page structure in a clear way. For many years I use layout pattern. Layout describes whole page as a template with blocks for header, menu, content, etc like on figure below. On page rendering these blocks are filled with data. I found a small code snipped for CI and improved it. Let’s start from simple usage example.

Simple Usage of Layout

 

1. Download and put Layout.php into application/libraries folder.

 

2. Create new default layout in views/layout/default.php with content:

 

1
2
3
4
5
6
7
8
9
10
<html>
 <head>
 <title>
<?=$title_for_layout?>
</title>
 </head>
 <body>
 <?=$content_for_layout?>
 </body>
 </html>

 

3. Create controller

 

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
 class Main extends CI_Controller {
 // Layout used in this controller
  public $layout_view = 'layout/default';
 public function index() {
 $this->load->library('layout');
 // Load layout library $this->layout->title('Site index page');
 // Set page title $data = array();
 $this->layout->view('index', $data);
 // Render view and layout
}
 }
 ?>

 

Simple. All data passed to the template in $data is also passed to the layout template.

Handling JS and CSS

This is first area of improvement. I added code to include most used external resources like JavaScript and CSS files. This way it’s possible to make optimizations later like stripping/minimizing content or combining into one file.

 

1
2
3
4
5
6
7
8
9
10
11
12
<?php
 class Main extends CI_Controller {
 public $layout_view = 'layout/default';
 public function index() {
 // Page local resource
$this->layout->js('js/index.js');
 $this->layout->css('css/index.css');
 $this->layout->title('Page title');
 $this->layout->view('index');
 }
 }
 ?>

 

Use this for layout/default.php to include resources. It contains two variable $css_for_layoutand $js_for_layout.

1
2
3
4
5
6
7
8
9
10
11
12
<html>
 <head>
 <title>
<?=$title_for_layout?>
</title>
 <?=$css_for_layout?>
 <?=$js_for_layout?>
 </head>
 <body>
 <?=$content_for_layout?>
 </body>
 </html>

 

Globalizing CI offers a way to create a parent class for all controllers in the project. It’s a very good place to put site global code. For example it is not convenient to specify default template in each controller file since sites usually have only one template. Same is related to resources like JS and CSS, some of them are global and must be included in each site page. Let’s create file in application/core/MY_Controller.php with content.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
 class MY_Controller extends CI_Controller {
 // Site global layout
  public $layout_view = 'layout/default';
 function __construct() {
 // Layout library loaded site wide
$this->load->library('layout');
 // Site global resources
$this->layout->js('js/jquery.min.js');
 $this->layout->css('css/site.css');
 }
 }
 ?>

 

Next is the controller class itself.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
 class Main extends MY_Controller {
 // Layout is not specified here, it is inherited from MY_Controller function __construct() {
 // Local resource used for all pages served by this controller
$this->layout->js('js/jlib.min.js');
 $this->layout->css('css/product.css');
 }
  public function index() {
 // Page specific resource
$this->layout->js('js/lib2.js');
 $this->layout->css('css/page.css');
 $this->layout->title('Page title');
 $this->layout->view('index');
 }
// This page uses different layout
  public function page2() {
 $this->layout_view = 'layout/short.php';
 $this->layout->title('Page title');
 $this->layout->view('index');
 }
 }
 ?>

 

Template Inheritance Like in Twig in CodeIgniter

Next area of improvement… Twig is a popular template engine available for PHP and it has a very nice feature called template inheritance. I personally do not see any practical usage of any template engines except PHP itself, but I love this feature and incorporated it here. Where to use it? Example: You want to implement breadcrumbs and they depend on what is current page. In your layout make a space for it anywhere with block function.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html>
 <head>
 <title>
<?=$title_for_layout?>
</title>
 <?=$css_for_layout?>
 <?=$js_for_layout?>
 </head>
 <body>
 <?$this->layout->block('breadcrumbs')?>
Site | <?$this->layout->block()?>
 <?=$content_for_layout?>
 </body>
 </html>

 

In page template include block with same name and it would be replaced in layout with content generated in template.

 

1
<?$this->layout->block('breadcrumbs')?>

 

Breadcrumbs for this page:

 

1
<?$this->layout->block()?>

 

Page content! Download full code here.

SynapseIndia Introduction to Clustering in PHP Development

It is almost an implicit standard for a modern web app/service to be fault tolerant and load balanced. Depending on the technologies involved, achieving a proper level of each can be difficult. This series will explore a few ways to handle each in PHP.

 

What Is Clustering?

An extremely simplified definition of clustering would be having multiple computers working together for a single goal. Typically you see it with distributed computing applications (network rendering of graphics, protein folding, etc.), but in the web world it is defined as having multiple servers providing a website or service. In practice, however, this can be more complicated especially when coupled with incorrect ideas around what clustering truly is.

 

Load Balancing

Load balancing is the first step in setting up a clustered environment for a web application. For those of you unfamiliar, load balancing consists of having a master node that accepts web requests, and funnels them to a farm of web servers to actually process the request.

 

From the diagram above, you can see that each server has its own session. Because of this, the load balancer needs to keep track of which server the user hit first, and keep redirecting them back to that same server on subsequent requests. This is accomplished by what is known as “sticky sessions.” Once a user has a session on a particular server, the load balancer redirects all of that user’s traffic back to that server.

 

On the surface, this setup appears to be clustering by the simple definition above, but in reality this setup only gives you load balancing, not fault tolerance–both of which are needed to have a proper cluster. If Server 1 goes offline, the load balancer will transfer those users to the remaining nodes, but their sessions will not follow them–effectively logging out every user on Server 1.

 

Sharing Sessions

For a cluster to work, not only do we need to load balance, but we also need to share the user sessions across all nodes. PHP is a bit unique in the sense that the session information is stored on the file system. To get proper PHP session sharing, every node essentially needs access to the other node’s filesystem.

 

NFS, A Simple Solution

One of the ways we can get proper session sharing in our cluster is to set up a NFS (Network File System) share on a central location, and have all of the PHP servers use it for session storage.

 

 

In this example, we have set up a NFS share on the load balancer, using it as the central session storage location. On each node, we need to mount the NFS share and change the PHP session storage location to be in this mount point (symlinks are fine here).

 

With this configuration, we have a true cluster. The request comes in and gets sent to an available node, and that node creates a session object on the NFS share. The next request comes in (with sticky sessions off) and gets redirected to another node. Since the first session object was created on the NFS share, the new node can read it in FROM the share and the user session continues. We can take down all of the server nodes except one and the site (with sessions) will remain up. The only drawback to this kind of set up is that we are relying on a single point of failure. The load balancer is controlling web traffic AND stores all of the session information. If it goes down, not only will we lose sessions, but the user traffic cannot get to the back end servers.