Friends

Quick Guide : Design Patterns for PHP - part III

The observer pattern
why?
To define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
One object makes itself observable by adding a method that allows another object, the observer, to register itself. When the observable object changes, it sends a message to the registered observers.

The participants classes in this pattern are:
Observable - interface or abstract class defining the operations for attaching and de-attaching observers to the client. 
ConcreteObservable - concrete Observable class. It maintain the state of the object and when a change in the state occurs it notifies the attached Observers.
Observer - interface or abstract class defining the operations to be used to notify this object.

A simple example is a list of users in a system. The code in Listing 4 shows a user list that sends out a message when users are added. This list is watched by a logging observer that puts out a message when a user is added.
Listing 4. Observer.php

<?php
interface IObserver
{
  function onChanged( $sender, $args );
}

interface IObservable
{
  function addObserver( $observer );
}

class UserList implements IObservable
{
  private $_observers = array();

  public function addCustomer( $name )
  {
    foreach( $this->_observers as $obs )
      $obs->onChanged( $this, $name );
  }

  public function addObserver( $observer )
  {
    $this->_observers []= $observer;
  }
}

class UserListLogger implements IObserver
{
  public function onChanged( $sender, $args )
  {
    echo( "'$args' added to user list\n" );
  }
}

$ul = new UserList();
$ul->addObserver( new UserListLogger() );
$ul->addCustomer( "Jack" );
?>


Output:

% php observer.php 
'Jack' added to user list
%

This code defines four elements: two interfaces and two classes. The IObservable interface defines an object that can be observed, and the UserList implements that interface to register itself as observable. The IObserver list defines what it takes to be an observer, and the UserListLogger implements that IObserver interface. This is shown in the UML in Figure 4.

Figure 4. The observable user list and the user list event logger
The observable user list and the user list event logger


The test code creates a UserList and adds the UserListLogger observer to it. Then the code adds a customer, and the UserListLogger is notified of that change.
It's critical to realize that the UserList doesn't know what the logger is going to do. There could be one or more listeners that do other things



In next post I will explain the forth design pattern "The chain-of-command pattern".



Quick Guide : Design Patterns for PHP - part II

The Singleton Pattern

Why?
1. If are using a reference to an object in mulitple location and you don't want the overhead of creating a new instance of that object for each refrence
e.g. Database connection object
2. To pass the objects state from one reference to another instead of starting from an initial state.

The singleton pattern covers this need. An object is a singleton if the application can include one and only one of that object at a time.

<?php
require_once("DB.php");

class DatabaseConnection
{
  public static function get()
  {
    static $db = null;
    if ( $db == null )
      $db = new DatabaseConnection();
    return $db;
  }

  private $_handle = null;

  private function __construct()
  {
    $dsn = 'mysql://root:password@localhost/photos';
    $this->_handle =& DB::Connect( $dsn, array() );
  }
  
  public function handle()
  {
    return $this->_handle;
  }
}

print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
?>


Output
% php singleton.php 
Handle = Object id #3
Handle = Object id #3
%
This code shows a single class called DatabaseConnection. You can't create your own DatabaseConnection because the constructor is private. But you can get the one and only one DatabaseConnection object using the static get method.

The database connection singleton
The two handles returned are the same object. If you use the database connection singleton across the application, you reuse the same handle everywhere.
You could use a global variable to store the database handle, but that approach only works for small applications. In larger applications, avoid globals, and go with objects and methods to get access to resources.

In next post I will explain the third design pattern "The observer pattern".

Quick Guide : Design Patterns for PHP


Design pattern provides useful ways for developing robust software faster along  with a way of encapsulating large ideas in friendly terms.  Most of the PHP programmer are not ware of the design patterns and how to implement those. So instead of going through the history and wasting more time in explanation, I will brief those patterns in short cut with examples.

The Factory pattern
The factory pattern is a class that has some methods that create objects for you. Instead of using new directly, you use the factory class to create objects. That way, if you want to change the types of objects created, you can change just the factory. All the code that uses the factory changes automatically.

What's the need to use Factory pattern?
Problem is tight coupling - Functions and classes in one part of the system rely too heavily on behaviors and structures in other functions and classes in other parts of the system. lots of code relies on a few key classes. Difficulties can arise when you need to change those classes. For example, suppose you have a User class that reads from a file. You want to change it to a different class that reads from the database, but all the code references the original class that reads from a file.

<?php
interface IUser
{
  function getName();
}

class User implements IUser
{
  public function __construct( $id ) { }

  public function getName()
  {
    return "Jack";
  }
}

class UserFactory
{
  public static function Create( $id )
  {
    return new User( $id );
  }
}

$uo = UserFactory::Create( 1 );
echo( $uo->getName()."\n" );
?>


Output
% php factory1.php 
Jack
%


Figure 1. The factory class and its related IUser interface and user class
The factory class and its related IUser interface and user class 

Advantage

suppose you need to first create the object and then set many attributes. This version of the factory pattern encapsulates that process in a single location so that the complex initialization code isn't copied and pasted all over the code base.

Listing 2. Factory2.php
<?php
interface IUser
{
  function getName();
}

class User implements IUser
{
  public static function Load( $id ) 
  {
        return new User( $id );
  }

  public static function Create( ) 
  {
        return new User( null );
  }

  public function __construct( $id ) { }

  public function getName()
  {
    return "Jack";
  }
}

$uo = User::Load( 1 );
echo( $uo->getName()."\n" );
?>


Output:

% php factory2.php 
Jack
%


Figure 2. The IUser interface and the user class with factory methods
The IUser interface and the user class with factory methods 









In my next part II will explain the Singleton pattern.


Part-II

Kick start developing your Own IPTV system - Part III

In this final post, here are the remaining steps described as follows
4.Streaming live broadcast video
                The first thing to simulate on your IPTV system is live TV that can be tuned into, and this can be done in two ways. The first is easy, the second is either painful or expensive. Live broadcast IPTV needs to be multicasted 24-7 over the IP network, as unicast is too inefficient. We will be streaming live TV from our video server.
               For each channel, we need to broadcast a 5 minute looping pre-captured video clip to a multicast IP address. For this, we can use the free VLC player, or the industry standard WinSend, created by Pixstream. The clip itself ideally needs to be previously encoded in MPEG-4 H.264 AVC, and formatted into an MPEG-2 transport stream. However, VLC being the Swiss army knife it is means we can convert open virtually any video file and encode it on the fly as we are broadcasting. Open your video file, and use the advanced options in VLC to stream the output onto the network as UDP, using a multicast address such as 235.5.5.5 to a random port (such as 10201).To validate the stream open the same network stream on other computer of VLC. Once they are broadcasting, the set-top box will be able to tune into the multicast stream just as VLC does.
5. Prepare VoD content
               Get the video files into the right format, and set them up to stream from a video server.Your video material will need to be pre-encoded in the same way the live multicast video is. Video is very temperamental and requires state control, unlike typical web protocols such as HTTP. RTP (real-time protocol) and RTSP (real-time streaming protocol) were designed to provide VCR-like controls for IP networks, and most, if not all commercial VoD servers use these technologies for delivering quality-assured video. A lot of set-top box manufacturers have adapted their hardware to be able to simulate VCR-like features using HTTP so video can be streamed directly from a web server like Apache. Once the video files have been pre-encoded, they need to be placed in the directory on the video server that has been allocated as the storage folder, as well as mirrored in the Apache web directory allocated on the web server.Almost all the RTSP servers have a web-based configuration panel and will need to index/identify each file for streaming. Once these are in place, test the RTSP capacity of the server by opening a network stream to them in VLC, and once any problems are corrected, your IP set-top box will play them using its in-built API.
6. Creating screens and menus
               Menus for the TV screen are created in HTML, CSS and Javascript, just as normal web pages are, using the same standard tools.The software on the device is an ordinary web browser like IE, Firefox, Opera or Safari, and overlays the web pages you create on the screen through the scart cable (OSD).
When the IP set-top box starts up and gains an IP address via DHCP, it will also request a “starting” URL of a web page from a web server, in the same way a PC web browser (e.g. IE, Firefox) will request a default home page.
              Producing screens for IPTV is almost the same as building an intranet site, with the only difference being that the HTML and Javascript contains set-top box-specific code that only the set-top box understands and executes.Each set-top box's hardware is different, so there is a different Javascript API for each device model that must be obtained from the manufacturer. Video can be displayed and scaled as any kind of image on the page, and manipulated by normal Javascript functions. The set-IP will not come with any software applications pre-installed (or even commands on the remote to go back or refresh the screen), so the very first application you need to create is an electronic programme guide (EPG) to navigate around your service and watch video streams.
               When mocking up screens in Photoshop, it is important to know that a standard definition PAL TV screen is 720 pixels wide by 576 pixels wide, before the so-called “safe area” is taken into account. Colour is considerably more primitive and much more sensitive to variance than on a desktop browser. The only input device available is a remote control with key codes similar to a desktop keyboard.
Using HTML for menu and screen displays means content can be dynamically generated using a server-side process just like any web page. The TV screen displays whatever you send it, meaning you can integrate any type of web-based system into your new IPTV network such as the Asterisk VoIP PBX, the Jabber IM server, multiplayer game servers, your own web application or an external XML API.
7. Publish
              The production procedure is exactly the same as it is for a website, only with TV-specific functionality and usability issues.

That's all. Once you have your network set up, its up to you to get creating menus and screens, and adding video content onto your video server that can be played back through the TV.



Kick start developing your Own IPTV system - Part II


In first part of post I have listed the prequisite/requirement to create the IPTv system. So are you ready with those ?
Let's start and understand each requirement

 We can use free open source software (FOSS) and adher to open standards wherever possible.
HTML screens and menus will be displayed using web server (e.g Apache). We can provide dynamic database driven content using server site scripting (e.g PHP & MySQL). Video needs to encode in MPEG-4 H.264 AVC, and packaged in a simple MPEG-2 transport stream. VLC and Helix Server can be used to stream out the video.
For more information on VLC refer http://www.videolan.org/vlc/streaming.html and Helix server ( Helix server)
1. Home for the kit
              How much space you need ? IPTV system won't need much space and two PCs (web server and video server) can be managed anywhere. PLC adaptors avoids cabling around. That's it. You just need space to give IPTV demo
2. Set-top box
              There are various IP set-top boxes which run different software and have different capabilities. To connect to the TV , we need a standard scart cable or RCA sockets, and display PAL/NTSC video at standard resolution. It's preferable if they have a web-based control panel, but many have proprietary configuration screens or use simple telnet. Firmware upgrades are best served with a remote TFTP server, such as that provided by vendors like SolarWinds.
The most popular choice of software is an embedded web browser, which for all intents and purposes does the same thing as a PC web browser like IE, Firefox, Opera or Safari. The developer interface tends to be a mark-up language, usually HTML/Javascript. The main embedded client software programs in use on IP set-top boxes today are Fresco/Galio (from Ant Plc), Opera, Escape/Evo (from Espial) and Myrio (based on Espial). You can think of them of little web browser units.
There are a lot of OEM vendors of IP set-top boxes to choose from all across the world. After searching across various sources i found Complete Media Systems, Amino, Kreatel (now Motorola), Vidanti, Tilgin (formely i3 Micro), ADB Global and Netgem.
3. Network setup
               IPTV runs over an IP network, so we can use existing jome or office network. It is better to create a new seperate network for TV due to hign traffic load.You can use any router or switch at all, which supports multicast.
If you're running all the screens and video from one server (for example, a portable laptop demo), you can even just use a simple crossover cable. Don't try and run video over a wireless connection.
An IP set-top box is just another network client device. When it is connected to the IP network, it is assigned an IP address by DHCP just as a desktop PC would be (this can also be static). If your router doesn't act as a DHCP server, you don't have a network gateway or are experiencing problems with a crossover cable, simply download and install a free DHCP server from the internet onto your web server PC.
PLC (powerline communication) adaptors create an Ethernet network over existing electricity cabling, which avoids the need to have wiring everywhere when you can't use wireless.

In last part of this post will continue with remaining steps.

Part III

Go back to Part I


Kick start developing your Own IPTV system

Are you planning to create your own IPTV system? you are at right point to start.

What you know about IPTV domain. If you google for term "IPTV", the wikipedia defines it as follows:

Internet Protocol television (IPTV) is a system through which Internet television services are delivered using the architecture and networking methods of the Internet Protocol Suite over a packet-switched network infrastructure, e.g., the Internet and broadband Internet access networks, instead of being delivered through traditional radio frequency broadcast, satellite signal, and cable television (CATV) formats.

IPTV is defined as multimedia services such as television/video/audio/text/graphics/data delivered over IP based networks managed to provide the required level of quality of service and experience, security, interactivity and reliability.

IPTV networks are basically intranet. If you've set up an intranet or public website, you can set up your own IPTV network and do what you want with it.
Webbrowser is not only made for PC's, it can also be on set-top box. You just need proper hardware and software.


Prequisites:
1. TV
2. IP set-top box
3. Multicast-capable router
4. Web server - (e.g Apache)
5. Video server
6. PLC Adaptors
7. Video files

In part two of this post, I will walk you through the process and details of each.

Security concerns while developing websites



Security threats/attacks for web sites which needs to take while developing web application

SQL Injection
In this attack, a user is able to execute SQL queries in your website's database. This attack is usually performed by entering text into a form field which causes a subsequent SQL query, generated from the PHP form processing code, to execute part of the content of the form field as though it were SQL. The effects of this attack range from the harmless (simply using SELECT to pull another data set) to the devastating (DELETE, for instance). In more subtle attacks, data could be changed, or new data added.

Directory Traversal
This attack can occur anywhere user-supplied data (from a form field or uploaded filename, for example) is used in a filesystem operation. If a user specifies “../../../../../../etc/passwd” as form data, and your script appends that to a directory name to obtain user-specific files, this string could lead to the inclusion of the password file contents, instead of the intended file. More severe cases involve file operations such as moving and deleting, which allow an attacker to make arbitrary changes to your filesystem structure.

Authentication Issues
Authentication issues involve users gaining access to something they shouldn't, but to which other users should. An example would be a user who was able to steal (or construct) a cookie allowing them to login to your site under an Administrator session, and therefore be able to change anything they liked.

Remote Scripts (XSS)
XSS, or Cross-Site Scripting (also sometimes referred to as CSS, but this can be confused with Cascading Style Sheets, something entirely different!) is the process of exploiting a security hole in one site to run arbitrary code on that site's server. The code is usually included into a running PHP script from a remote location. This is a serious attack which could allow any code the attacker chooses to be run on the vulnerable server, with all of the permissions of the user hosting the script, including database and filesystem access.

Twitter Delicious Facebook Digg Stumbleupon Favorites More