Sunday, December 28, 2014

what is class map in zend?

The Class Map Generator utility: bin/classmap_generator.php

Overview

The script bin/classmap_generator.php can be used to generate class map files for use with the ClassMapAutoloader.
Internally, it consumes both Zend\Console\Getopt (for parsing command-line options) and Zend\File\ClassFileLocator for recursively finding all PHP class files in a given tree.

Quick Start

You may run the script over any directory containing source code. By default, it will look in the current directory, and will write the script to autoloader_classmap.php in the directory you specify.
1
php classmap_generator.php Some/Directory/

Configuration Options

–help or -h
Returns the usage message. If any other options are provided, they will be ignored.
–library or -l
Expects a single argument, a string specifying the library directory to parse. If this option is not specified, it will assume the current working directory.
–output or -o
Where to write the autoload class map file. If not provided, assumes “autoload_classmap.php” in the library directory.
–append or -a
Append to autoload file if it exists.
–overwrite or -w
If an autoload class map file already exists with the name as specified via the --output option, you can overwrite it by specifying this flag. Otherwise, the script will not write the class map and return a warning.

how to create a simple album module in zend

Setting up the Album module

Start by creating a directory called Album under module with the following subdirectories to hold the module’s files:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
 zf2-tutorial/
     /module
         /Album
             /config
             /src
                 /Album
                     /Controller
                     /Form
                     /Model
             /view
                 /album
                     /album
As you can see the Album module has separate directories for the different types of files we will have. The PHP files that contain classes within the Album namespace live in the src/Album directory so that we can have multiple namespaces within our module should we require it. The view directory also has a sub-folder called album for our module’s view scripts.
In order to load and configure a module, Zend Framework 2 has a ModuleManager. This will look for Module.php in the root of the module directory (module/Album) and expect to find a class called Album\Module within it. That is, the classes within a given module will have the namespace of the module’s name, which is the directory name of the module.
Create Module.php in the Album module: Create a file called Module.php under zf2-tutorial/module/Album:
 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
 namespace Album;

 use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
 use Zend\ModuleManager\Feature\ConfigProviderInterface;

 class Module implements AutoloaderProviderInterface, ConfigProviderInterface
 {
     public function getAutoloaderConfig()
     {
         return array(
             'Zend\Loader\ClassMapAutoloader' => array(
                 __DIR__ . '/autoload_classmap.php',
             ),
             'Zend\Loader\StandardAutoloader' => array(
                 'namespaces' => array(
                     __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                 ),
             ),
         );
     }

     public function getConfig()
     {
         return include __DIR__ . '/config/module.config.php';
     }
 }
The ModuleManager will call getAutoloaderConfig() and getConfig() automatically for us.

Autoloading files

Our getAutoloaderConfig() method returns an array that is compatible with ZF2’s AutoloaderFactory. We configure it so that we add a class map file to the ClassMapAutoloader and also add this module’s namespace to the StandardAutoloader. The standard autoloader requires a namespace and the path where to find the files for that namespace. It is PSR-0 compliant and so classes map directly to files as per the PSR-0 rules.
As we are in development, we don’t need to load files via the classmap, so we provide an empty array for the classmap autoloader. Create a file called autoload_classmap.php under zf2-tutorial/module/Album:
1
 return array();
As this is an empty array, whenever the autoloader looks for a class within the Album namespace, it will fall back to the to StandardAutoloader for us.
Note
If you are using Composer, you could instead just create an empty getAutoloaderConfig() { } and add to composer.json:
1
2
3
 "autoload": {
     "psr-0": { "Album": "module/Album/src/" }
 },
If you go this way, then you need to run php composer.phar update to update the composer autoloading files.

Configuration

Having registered the autoloader, let’s have a quick look at the getConfig() method in Album\Module. This method simply loads the config/module.config.php file.
Create a file called module.config.php under zf2-tutorial/module/Album/config:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
 return array(
     'controllers' => array(
         'invokables' => array(
             'Album\Controller\Album' => 'Album\Controller\AlbumController',
         ),
     ),
     'view_manager' => array(
         'template_path_stack' => array(
             'album' => __DIR__ . '/../view',
         ),
     ),
 );
The config information is passed to the relevant components by the ServiceManager. We need two initial sections: controllers and view_manager. The controllers section provides a list of all the controllers provided by the module. We will need one controller, AlbumController, which we’ll reference as Album\Controller\Album. The controller key must be unique across all modules, so we prefix it with our module name.
Within the view_manager section, we add our view directory to the TemplatePathStack configuration. This will allow it to find the view scripts for the Album module that are stored in our view/ directory.

Informing the application about our new module

We now need to tell the ModuleManager that this new module exists. This is done in the application’s config/application.config.php file which is provided by the skeleton application. Update this file so that its modules section contains the Album module as well, so the file now looks like this:
(Changes required are highlighted using comments.)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
 return array(
     'modules' => array(
         'Application',
         'Album',                  // <-- Add this line
     ),
     'module_listener_options' => array(
         'config_glob_paths'    => array(
             'config/autoload/{,*.}{global,local}.php',
         ),
         'module_paths' => array(
             './module',
             './vendor',
         ),
     ),
 );
As you can see, we have added our Album module into the list of modules after the Application module.
Step create using command : zf.php create module modulename (or zf2.php if using zf2).

Tuesday, November 18, 2014

how to get CKeditor value using javascript[Solve]

<script jang="javascript">

var xvalue=CKEDITOR.instances['myTextarea'].getData();

alert(xvalue);

</script>

Thursday, November 13, 2014

how to search one view used in other views in oracle?

SELECT * FROM User_Dependencies
WHERE TYPE IN
('PACKAGE',
'PACKAGE BODY', 'TYPE BODY',
'TRIGGER',
'FUNCTION',
'VIEW',
'SYNONYM',
'TYPE'
)
AND REFERENCED_OWNER = 'SERVERDB'
AND REFERENCED_NAME = 'SERVERS_V';


What main different between session and cache?

The first main difference between session and caching is: a session is per-user based but caching is not per-user based, So what does that mean? Session data is stored at the user level but caching data is stored at the application level and shared by all the users. It means that it is simply session data that will be different for the various users for all the various users, session memory will be allocated differently on the server but for the caching only one memory will be allocated on the server and if one user modifies the data of the cache for all, the user data will be modified.

Tuesday, November 11, 2014

zend framework interview questions and answers for experienced

Question: How to disable layout from controller?

?
1
$this->_helper->layout()->disableLayout();


Disable Zend Layout from controller for Ajax call only
?
1
2
3
if($this->getRequest()->isXmlHttpRequest()){
    $this->_helper->layout()->disableLayout();
}


How to change the View render file from controller?
?
1
2
3
4
function listAction(){
    //call another view file file
    $this->render("anotherViewFile");
}


How to protect your site from sql injection in zend when using select query?
?
1
2
3
4
5
$select = $this->select()               
                ->from(array('u' => 'users'), array('id', 'username'))
                ->where('name like ?',"%php%")
                ->where('user_id=?','5')
                ->where('rating<=?',10);



How to check post method in zend framework?
?
1
2
3
4
5
if($this->getRequest()->isPost()){
    //Post
}else{
//Not post
}


How to get all POST data?
?
1
$this->getRequest()->getPost();


How to get all GET data?
?
1
$this->getRequest()->getParams();


How to redirect to another page from controller?
?
1
$this->_redirect('/users/login');


How to get variable's value from get?
?
1
$id= $this->getRequest()->getParam('id');


Create Model file in zend framework?
?
1
2
3
4
class Application_Model_Users extends Zend_Db_Table_Abstract {
    protected $_name = "users";
    protected $_primary = "id";     
}


How to create object of Model?
?
1
$userObj = new Application_Model_Users();


Which Class extend the Zend Controller?
Zend_Controller_Action
For Example
?
1
2
class AjaxController extends Zend_Controller_Action {
}


Which Class extend the zend Model?
Zend_Db_Table_Abstract
For Example
?
1
class Application_Model_Users extends Zend_Db_Table_Abstract { }


What is a framework?
In software development, a framework is a defined support structure in which another software project can be organized and developed.


Why should we use framework?
Framework is a structured system where we get following things
Rapid application development(RAD).
Source codes become more manageable.
Easy to extend features.


Where we set configuration in zend framework?
We set the config in application.ini which is located in application/configs/application.ini.


What is Front Controller?
It used Front Controller pattern. zend also use singleton pattern.
=> routeStartup: This function is called before Zend_Controller_Front calls on the router to evaluate the request.
=> routeShutdown: This function is called after the router finishes routing the request.
=> dispatchLoopStartup: This is called before Zend_Controller_Front enters its dispatch loop.
=> preDispatch: called before an action is dispatched by the dispatcher.
=> postDispatch: is called after an action is dispatched by the dispatcher.


What is full form of CLA in Zend Framework?
Contributor License Agreement


Should I sign an individual CLA or a corporate CLA?
If you are contributing code as an individual- and not as part of your job at a company- you should sign the individual CLA. If you are contributing code as part of your responsibilities as an employee at a company, you should submit a corporate CLA with the names of all co-workers that you foresee contributing to the project.


How to include js from controller and view in Zend?
From within a view file: $this->headScript()->appendFile('filename.js'); From within a controller: $this->view->headScript()->appendFile('filename.js'); And then somewhere in your layout you need to echo out your headScript object: $this->headScript();


What are Naming Convention for PHP File?
1. There should not any PHP closing tag (?>)in controller & Model file.
2. Indentation should consist of 4 spaces. Tabs are not allowed.
3. The target line length is 80 characters, The maximum length of any line of PHP code is 120 characters.
4. Line termination follows the Unix text file convention. Lines must end with a single linefeed (LF) character. Linefeed characters are represented as ordinal 10, or hexadecimal 0x0A


What are Naming Convention for Classes, Interfaces, FileNames, Functions, Methods, Variables and constants?
http://framework.zend.com/manual/1.11/en/coding-standard.naming-conventions.html


What are coding style of Zend Framework?
http://framework.zend.com/manual/1.12/en/coding-standard.coding-style.html


What is Front Controller in Zend Framework?
Zend used Front Controller pattern for rendering the data. It also use singleton pattern.
=> routeStartup: This function is called before Zend_Controller_Front calls on the router to evaluate the request.
=> routeShutdown: This function is called after the router finishes routing the request.
=> dispatchLoopStartup: This is called before Zend_Controller_Front enters its dispatch loop.
=> preDispatch: called before an action is dispatched by the dispatcher.
=> postDispatch: is called after an action is dispatched by the dispatcher.

How to use update statemnet in Zend Framework?
?
1
2
3
4
5
6
7
8
9
  class Application_Model_Users extends Zend_Db_Table_Abstract {
    protected $_name = 'users';
    protected $_primary = 'id';
  
    function updateData($updateData = array()) {
        //please update dynamic data
        $this->update(array('name' => 'arun', 'type' => 'user'), array('id=?' => 10));
    }
}


How we can do multiple column ordering in Zend Framework?











  class Application_Model_Users extends Zend_Db_Table_Abstract {
    protected $_name = 'users';
    protected $_primary = 'id';
  
    function users() {
        $select = $this->select()
        ->setIntegrityCheck(false)
        ->from(array('u' => 'users'), array('name as t_name'))->order('first_name asc')->order('last_name des');
         return $this->fetchAll($select);
    }
  
}

How do you protect your site from sql injection in zend when using select query?

You have to quote the strings,

$this->getAdapter ()->quote ( );

$select->where ( " = ", );

OR (If you are using the question mark after equal to sign)

$select->where ( " = ? ", );

How to include css from controller and view in zend?


include within a view file: $this->headLink()->appendStylesheet(‘filename.css’);

include  within a controller: $this->view->headLink()->appendStylesheet(‘filename.css’);

And then somewhere in your layout you need to echo out your headLink object:

headLink();?>

Saturday, October 25, 2014

how to use ckeditor using php?[Solved]

 
 
Easy steps to Integrate ckeditor with php pages
step 1 : download the ckeditor.zip file
step 2 : paste ckeditor.zip file on root directory of the site or you can paste it where the files are (i did this one )
step 3 : extract the ckeditor.zip file
step 4 : open the desired php page you want to integrate with here page1.php
step 5 : add some javascript first below, this is to call elements of ckeditor and styling and css without this you will only a blank textarea
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
And if you are using in other sites, then use relative links for that here is one below
<script type="text/javascript" src="somedirectory/ckeditor/ckeditor.js"></script>
step 6 : now!, you need to call the work code of ckeditor on your page page1.php below is how you call it
<?php
// Make sure you are using a correct path here.
include_once 'ckeditor/ckeditor.php';

$ckeditor = new CKEditor();
$ckeditor->basePath = '/ckeditor/';
$ckeditor->config['filebrowserBrowseUrl'] = '/ckfinder/ckfinder.html';
$ckeditor->config['filebrowserImageBrowseUrl'] = '/ckfinder/ckfinder.html?type=Images';
$ckeditor->config['filebrowserFlashBrowseUrl'] = '/ckfinder/ckfinder.html?type=Flash';
$ckeditor->config['filebrowserUploadUrl'] = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
$ckeditor->config['filebrowserImageUploadUrl'] = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
$ckeditor->config['filebrowserFlashUploadUrl'] = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';
$ckeditor->editor('CKEditor1');

?>
step 7 : what ever you name you want, you can name to it ckeditor by changing the step 6 code last line
$ckeditor->editor('mycustomname');
step 8 : Open-up the page1.php, see it, use it, share it and Enjoy because we all love Open Source.
Hope enjoy.!!   :)

Other way to call the ckeditor
Step below :
<?php require("ckeditor/ckeditor.php"); ?>

 <script type="text/javascript" src="ckeditor/ckeditor.js"></script>
 <script type="text/javascript" src="somedirectory/ckeditor/ckeditor.js"></script>

<textarea class="ckeditor" name="editor1"></textarea>

Friday, September 26, 2014

how to create cache file work using php

High-traffic sites can often benefit from caching of pages, to save processing of the same data over and over again. This caching tutorial runs through the basics of file caching in PHP.
Caching of output in PHP is made easier by the use of the output buffering functions built in to PHP 4 and above.
You'll need to use two files to set up a caching system for your site. The first, "begin_caching.php" in this case, will run before any other PHP on your site. The second, "end_caching.php" in this case, runs after normal scripts have run. The two scripts effectively wrap around your current site.
You can achieve this wrapping effect one of two ways. The first way is to simply use the include() function and add them manually to every script you run. Unfortunately, this method can take some time, but is arguably more portable than the alternative.
The alternative relies on adding the following two lines of code (modified to reflect the correct path to the two PHP files needed) to your htaccess file. This is my preferred method, just because it requires no modification to existing scripts, and can very easily and quickly be turned off (just by commenting out the relevant lines in the htaccess file).
  1. php_value auto_prepend_file /full/path/to/begin_caching.php
  2. php_value auto_append_file /full/path/to/end_caching.php
Next, we move on to the scripts that do the work. There are several stages to caching a document:
  1. Receive request for page
  2. Check for the existence of a cached version of that page
  3. Check the cached copy is still valid
    • If it is, send the cached copy
    • If not, create a new cached copy and send it
To begin with, the script below contains a few basic settings. Here, you can set the directory you want to save cached files to (I would recommend keeping that directory outside your web root directory or at least protecting it from view through a normal browser). This script will need to be able to create files in this directory, and you need to allow this by setting the permissions of the directory. The permissions depend upon your server set up, so you may want to start by setting them to 777 while testing the script, and then reduce them to the lowest levels possible once the script is working.
You can also set the time, in seconds, a cached file should be considered valid for after creation, and set the file extension for saved files. It would be wise to not name them ".php", just for safety's sake.
  1. <?php
  2. // Settings
  3. $cachedir = '../cache/'; // Directory to cache files in (keep outside web root)
  4. $cachetime = 600; // Seconds to cache files for
  5. $cacheext = 'cache'; // Extension to give cached files (usually cache, htm, txt)
  6. // Ignore List
  7. $ignore_list = array(
  8. 'addedbytes.com/rss.php',
  9. 'addedbytes.com/search/'
  10. );
  11. // Script
  12. $page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; // Requested page
  13. $cachefile = $cachedir . md5($page) . '.' . $cacheext; // Cache file to either load or create
  14. $ignore_page = false;
  15. for ($i = 0; $i < count($ignore_list); $i++) {
  16. $ignore_page = (strpos($page, $ignore_list[$i]) !== false) ? true : $ignore_page;
  17. }
  18. $cachefile_created = ((@file_exists($cachefile)) and ($ignore_page === false)) ? @filemtime($cachefile) : 0;
  19. @clearstatcache();
  20. // Show file from cache if still valid
  21. if (time() - $cachetime < $cachefile_created) {
  22. //ob_start('ob_gzhandler');
  23. @readfile($cachefile);
  24. //ob_end_flush();
  25. exit();
  26. }
  27. // If we're still here, we need to generate a cache file
  28. ob_start();
  29. ?>
The file starts by generating an MD5 hash of the page that has been requested. It will use the complete requested URL, and the MD5 hash will be a 32 digit number, unique for each file. It then checks for the existence of this file.
If the file exists, it checks to see when it was last updated. If the file is older than the allowed time, it acts as though no cache existed (carrying on and generating a new file). If the file is still valid, it simply displays it.
There is also, in the settings, a list of pages to ignore when caching. This can be search results, comments pages, a news page or news feed - anything that should always be up to date. Simply add anything you do not want cached into here, and it will not be cached. You can add directories, or parts of URLs - the above simply searches for a text string. In the example above, I have left out the "http://www" portion of the URL, as this can be missed out by some visitors.
Finally, the two lines in italics above are both commented out. You can, if you like, uncomment these, and that will use outbut buffering to gzip your content before sending it to users, making your site even faster for them. Please note, though, that output buffering with gz encoding is not available in versions of PHP previous to 4.0.5.
Which brings us to the second file, "end_caching.php". At the end of the first file, if no cache exists, we start output buffering. This means that rather than send the page to the user, we are saving it for use later. In the second script below, we take the contents of the output buffer, and write it to a file.
<?php

    // Now the script has run, generate a new cache file
    $fp = @fopen($cachefile, 'w'); 

    // save the contents of output buffer to the file
    @fwrite($fp, ob_get_contents());
    @fclose($fp); 

    ob_end_flush(); 

?>
Important: If you do not have "register_globals" set to off in php.ini, make sure you add the following to the beginning of "end_caching.php" (straight after the "<?php" line) to aid security. This will ensure that an attacker cannot visit "end_caching.php" directly and overwrite an important file on your site (or read its contents).
    $cachedir = '../cache/'; // Directory to cache files in (keep outside web root)
    $cacheext = 'cache'; // Extension to give cached files (usually cache, htm, txt)
    $page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; // Requested page
    $cachefile = $cachedir . md5($page) . '.' . $cacheext; // Cache file to either load or create
And there we have it. If a cached document exists, it is shown to the user, and if not, one is created.
Finally, you need to make sure the cache remains reasonably clean. Over time, out of date or redundant files could build up, and these should be removed regularly. For this reason, I usually set up an automated script to delete all cache files once a week (or less often, depending on the traffic of the site), but this will depend greatly upon the server software you are using.
The script below is one example of a script to delete all cache files. You will need to set the cache directory at the beginning before running the script. You can either use this manually, visiting the page through your browser whenever you want to empty the cache, or run it automatically. An example of a CRON job used to run this script automatically is below the script (the " >/dev/null 2>&1" bit at the end of the crontab prevents the server emailing me every time the script runs). Please note that this last script will be cached too, unless you specify otherwise!
<?php

    // Settings
    $cachedir = '../cache/'; // Directory to cache files in (keep outside web root)

    if ($handle = @opendir($cachedir)) {
        while (false !== ($file = @readdir($handle))) {
            if ($file != '.' and $file != '..') {
                echo $file . ' deleted.<br>';
                @unlink($cachedir . '/' . $file);
            }
        }
        @closedir($handle);
    }

?>
curl http://www.your_domain.com/empty_caching.php >/dev/null 2>&1

Monday, September 22, 2014

get facebook friends list using php api

Graph API Reference /{user-id}/friends

A person's friends.

Reading

/* PHP SDK v4.0.0 */
/* make the API call */
$request = new FacebookRequest(
  $session,
  'GET',
  '/me/friends'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */

Permissions

  • A user access token with user_friends permission is required to view the current person's friends.
  • This will only return any friends who have used (via Facebook Login) the app making the request.
  • If a friend of the person declines the user_friends permission, that friend will not show up in the friend list for this person.

Modifiers

You can append another person's id to the edge in order to determine whether that person is friends with the root node user:
/* PHP SDK v4.0.0 */
/* make the API call */
$request = new FacebookRequest(
  $session,
  'GET',
  '/{user-id-a}/friends/{user-id-b}'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */
If user-a is friends with user-b in the above request, the response will contain the User object for user-b. If they are not friends, it will return an empty dataset.

Fields

An array of User objects representing the person's friends with this additional field:
NameDescriptionType
summaryAn object containing summary info about this edge.object

Publishing

You can't publish using this edge.

Deleting

You can't delete using this edge.

Updating

You can't update using this edge.

Sunday, August 24, 2014

php top list common PHP design patterns

Design patterns were introduced to the software community in Design Patterns, by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (colloquially known as the "gang of four"). The core concept behind design patterns, presented in the introduction, was simple. Over their years of developing software, Gamma et al found certain patterns of solid design emerging, just as architects designing houses and buildings can develop templates for where a bathroom should be located or how a kitchen should be configured. Having those templates, or design patterns, means they can design better buildings more quickly. The same applies to software.
Design patterns not only present useful ways for developing robust software faster but also provide a way of encapsulating large ideas in friendly terms. For example, you can say you're writing a messaging system to provide for loose coupling, or you can say you're writing an observer, which is the name of that pattern.
It's difficult to demonstrate the value of patterns using small examples. They often look like overkill because they really come into play in large code bases. This article can't show huge applications, so you need to think about ways to apply the principles of the example -- and not necessarily this exact code -- in your larger applications. That's not to say that you shouldn't use patterns in small applications. Most good applications start small and become big, so there is no reason not to start with solid coding practices like these.
Now that you have a sense of what design patterns are and why they're useful, it's time to jump into five common patterns for PHP V5.

The factory pattern

Many of the design patterns in the original Design Patterns book encourage loose coupling. To understand this concept, it's easiest to talk about a struggle that many developers go through in large systems. The problem occurs when you change one piece of code and watch as a cascade of breakage happens in other parts of the system -- parts you thought were completely unrelated.
The 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. You need a set of patterns that lets these classes talk with each other, but you don't want to tie them together so heavily that they become interlocked.
In large systems, 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. This is where the factory pattern comes in handy.
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.
Listing 1 shows an example of a factory class. The server side of the equation comes in two pieces: the database, and a set of PHP pages that let you add feeds, request the list of feeds, and get the article associated with a particular feed.
Listing 1. Factory1.php
<?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" );
?>
An interface called IUser defines what a user object should do. The implementation of IUser is called User, and a factory class called UserFactory creates IUser objects. This relationship is shown as UML in Figure 1.
Figure 1. The factory class and its related IUser interface and user class
The factory class and its related IUser interface and user classIf you run this code on the command line using the php interpreter, you get this result:
% php factory1.php 
Jack
%
The test code asks the factory for a User object and prints the result of the getName method.
A variation of the factory pattern uses factory methods. These public static methods in the class construct objects of that type. This approach is useful when creating an object of this type is nontrivial. For example, 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 shows an example of using factory methods.
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" );
?>
This code is much simpler. It has only one interface, IUser, and one class called User that implements the interface. The User class has two static methods that create the object. This relationship is shown in UML in Figure 2.
Figure 2. The IUser interface and the user class with factory methods
The IUser interface and the user class with factory methodsRunning the script on the command line yields the same result as the code in Listing 1, as shown here:
% php factory2.php 
Jack
%
As stated, sometimes such patterns can seem like overkill in small situations. Nevertheless, it's still good to learn solid coding forms like these for use in any size of project.

The singleton pattern

Some application resources are exclusive in that there is one and only one of this type of resource. For example, the connection to a database through the database handle is exclusive. You want to share the database handle in an application because it's an overhead to keep opening and closing connections, particularly during a single page fetch.
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. The code in Listing 3 shows a database connection singleton in PHP V5.
Listing 3. Singleton.php
<?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" );
?>
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 UML for this code is shown in Figure 3.
Figure 3. The database connection singleton
The database connection singletonThe proof in the pudding is that the database handle returned by the handle method is the same between two calls. You can see this by running the code on the command line.
% php singleton.php 
Handle = Object id #3
Handle = Object id #3
%
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.

The observer pattern

The observer pattern gives you another way to avoid tight coupling between components. This pattern is simple: 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. What those observers do with that information isn't relevant or important to the observable object. The result is a way for objects to talk with each other without necessarily understanding why.
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" );
?>
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 loggerIf you run this on the command line, you see this output:
% php observer.php 
'Jack' added to user list
%
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. For example, you may have an observer that sends a message to the new user, welcoming him to the system. The value of this approach is that the UserList is ignorant of all the objects depending on it; it focuses on its job of maintaining the user list and sending out messages when the list changes.
This pattern isn't limited to objects in memory. It's the underpinning of the database-driven message queuing systems used in larger applications.

The chain-of-command pattern

Building on the loose-coupling theme, the chain-of-command pattern routes a message, command, request, or whatever you like through a set of handlers. Each handler decides for itself whether it can handle the request. If it can, the request is handled, and the process stops. You can add or remove handlers from the system without influencing other handlers. Listing 5 shows an example of this pattern.
Listing 5. Chain.php
<?php
interface ICommand
{
  function onCommand( $name, $args );
}

class CommandChain
{
  private $_commands = array();

  public function addCommand( $cmd )
  {
    $this->_commands []= $cmd;
  }

  public function runCommand( $name, $args )
  {
    foreach( $this->_commands as $cmd )
    {
      if ( $cmd->onCommand( $name, $args ) )
        return;
    }
  }
}

class UserCommand implements ICommand
{
  public function onCommand( $name, $args )
  {
    if ( $name != 'addUser' ) return false;
    echo( "UserCommand handling 'addUser'\n" );
    return true;
  }
}

class MailCommand implements ICommand
{
  public function onCommand( $name, $args )
  {
    if ( $name != 'mail' ) return false;
    echo( "MailCommand handling 'mail'\n" );
    return true;
  }
}

$cc = new CommandChain();
$cc->addCommand( new UserCommand() );
$cc->addCommand( new MailCommand() );
$cc->runCommand( 'addUser', null );
$cc->runCommand( 'mail', null );
?>
This code defines a CommandChain class that maintains a list of ICommand objects. Two classes implement the ICommand interface -- one that responds to requests for mail and another that responds to adding users. The UML is shows in Figure 5.
Figure 5. The command chain and its related commands
The command chain and its related commandsIf you run the script, which contains some test code, you see the following output:
% php chain.php 
UserCommand handling 'addUser'
MailCommand handling 'mail'
%
The code first creates a CommandChain object and adds instances of the two command objects to it. It then runs two commands to see who responds to those commands. If the name of the command matches either UserCommand or MailCommand, the code falls through and nothing happens.
The chain-of-command pattern can be valuable in creating an extensible architecture for processing requests, which can be applied to many problems.

The strategy pattern

The last design pattern we will cover is the strategy pattern. In this pattern, algorithms are extracted from complex classes so they can be replaced easily. For example, the strategy pattern is an option if you want to change the way pages are ranked in a search engine. Think about a search engine in several parts -- one that iterates through the pages, one that ranks each page, and another that orders the results based on the rank. In a complex example, all those parts would be in the same class. Using the strategy pattern, you take the ranking portion and put it into another class so you can change how pages are ranked without interfering with the rest of the search engine code.
As a simpler example, Listing 6 shows a user list class that provides a method for finding a set of users based on a plug-and-play set of strategies.
Listing 6. Strategy.php
<?php
interface IStrategy
{
  function filter( $record );
}

class FindAfterStrategy implements IStrategy
{
  private $_name;

  public function __construct( $name )
  {
    $this->_name = $name;
  }

  public function filter( $record )
  {
    return strcmp( $this->_name, $record ) <= 0;
  }
}

class RandomStrategy implements IStrategy
{
  public function filter( $record )
  {
    return rand( 0, 1 ) >= 0.5;
  }
}

class UserList
{
  private $_list = array();

  public function __construct( $names )
  {
    if ( $names != null )
    {
      foreach( $names as $name )
      {
        $this->_list []= $name;
      }
    }
  }

  public function add( $name )
  {
    $this->_list []= $name;
  }

  public function find( $filter )
  {
    $recs = array();
    foreach( $this->_list as $user )
    {
      if ( $filter->filter( $user ) )
        $recs []= $user;
    }
    return $recs;
  }
}

$ul = new UserList( array( "Andy", "Jack", "Lori", "Megan" ) );
$f1 = $ul->find( new FindAfterStrategy( "J" ) );
print_r( $f1 );

$f2 = $ul->find( new RandomStrategy() );
print_r( $f2 );
?>
The UML for this code is shown in Figure 6.
Figure 6. The user list and the strategies for selecting users
The user list and the strategies for selecting usersThe UserList class is a wrapper around an array of names. It implements a find method that takes one of several strategies for selecting a subset of those names. Those strategies are defined by the IStrategy interface, which has two implementations: One chooses users randomly and the other chooses all the names after a specified name. When you run the test code, you get the following output:
% php strategy.php 
Array
(
    [0] => Jack
    [1] => Lori
    [2] => Megan
)
Array
(
    [0] => Andy
    [1] => Megan
)
%

Top Design pattern and Software design interview questions for Programmers

Design patterns and software design questions are essential part of any programming interview, no matter whether you are going for Java interview or C#  interview. In face programming and design skill complement each other quite well, people who are good programmer are often a good designer as well as they know how to break a problem in to piece of code or software design but these skill just doesn’t come. You need to keep designing, programming both small scale and large scale systems and keep learning from mistakes.Learning about Object oriented design principles is a good starting point. Anyway this article is about some design questions which has been repeatedly asked in various interviews. I have divided them on two category for beginners and intermediate for sake of clarity and difficulty level.

These are questions which not only relates to design patterns but also related to software design. These questions requires some amount of thinking and experience to answer. In most of the cases interviewer is not looking for absolute answers but looking for your approach, how do you think about a problem, do you able to think through, do you able to bring out things which are not told to you. This is where experience come in picture, What are things you consider while solving a problem etc. overall these design questions kicks off your thought process. Some time interviewer ask you to write code as well so be prepare for that. you can excel in these questions if you know the concept, example and application of your programming and design skill.
1. Give an example where you prefer abstract class over interface ?
This is common but yet tricky design interview question. both interface and abstract class follow "writing code for interface than implementation" design principle which adds flexibility in code, quite important to tackle with changing requirement. here are some pointers which help you to answer this question:
1. In Java you can only extend one class but implement multiple interface. So if you extend a class you lost your chance of extending another class.
2. Interface are used to represent adjective or behavior e.g. Runnable, Clonable, Serializable etc, so if you use an abstract class to represent behavior your class can not be Runnable and Clonable at same time because you can not extend two class in Java but if you use interface your class can have multiple behavior at same time.
3. On time critical application prefer abstract class is slightly faster than interface.
4. If there is a genuine common behavior across the inheritance hierarchy which can be coded better at one place than abstract class is preferred choice. Some time interface and abstract class can work together also where defining function in interface and default functionality on abstract class.
To learn more about interface in Java check my post 10 things to know about Java interfaces
2. Design a Vending Machine which can accept different coins, deliver different products?
This is an open design question which you can use as exercise, try producing design document, code and Junit test rather just solving the problem and check how much time it take you to come to solution and produce require artifacts, Ideally this question should be solve in 3 hours, at least a working version.
3. You have a Smartphone class and will have derived classes like IPhone, AndroidPhone,WindowsMobilePhone
can be even phone names with brand, how would you design this system of Classes.
This is another design pattern exercise where you need to apply your object oriented design skill to come with a design which is flexible enough to support future products and stable enough to support changes in existing model.
4. When do you overload a method in Java and when do you override it ?
Rather a simple question for experienced designer in Java. if you see different implementation of a class has different way of doing certain thing than overriding is the way to go while overloading is doing same thing but with different input. method signature varies in case of overloading but not in case of overriding in java.
5. Design ATM Machine ?
We all use ATM (Automated Teller Machine) , Just think how will you design an ATM ? for designing financial system one must requirement is that they should work as expected in all situation. so no matter whether its power outage ATM should maintain correct state (transactions), think about locking, transaction, error condition, boundary condition etc. even if you not able to come up exact design but if you be able to point out non functional requirement, raise some question , think about boundary condition will be good progress.
6. You are writing classes to provide Market Data and you know that you can switch to different vendors overtime like Reuters, wombat and may be even to direct exchange feed , how do you design your Market Data system.
This is very interesting design interview question and actually asked in one of big investment bank and rather common scenario if you have been writing code in Java. Key point is you will have a MarketData interface which will have methods required by client e.g. getBid(), getPrice(), getLevel() etc and MarketData should be composed with a MarketDataProvider by using dependency injection. So when you change your MarketData provider Client won't get affected because they access method form MarketData interface or class.
7. Why is access to non-static variables not allowed from static methods in Java
You can not access non-static data from static context in Java simply because non-static variables are associated with a particular instance of object while Static is not associated with any instance. You can also see my post why non static variable are not accessible in static context for more detailed discussion.
8. Design a Concurrent Rule pipeline in Java?
Concurrent programming or concurrent design is very hot now days to leverage power of ever increasing cores in
advanced processor and Java being a multi-threaded language has benefit over others. Do design a concurrent system key point to note is thread-safety, immutability, local variables and avoid using static or instance variables. you just to think that one class can be executed by multiple thread a same time, So best approach is that every thread work on its own data, doesn't interfere on other data and have minimal synchronization preferred at start of pipeline. This question can lead from initial discussion to full coding of classes and interface but if you remember key points and issues around concurrency e.g. race condition, deadlock, memory interference, atomicity, ThreadLocal variables  etc you can get around it.

Design pattern interview questions for Beginners

These software design and design pattern questions are mostly asked at beginners level and just informative purpose that how much candidate is familiar with design patterns like does he know what is a design pattern or what does a particular design pattern do ? These questions can easily be answered by memorizing the concept but still has value in terms of information and knowledge.
1. What is design patterns ? Have you used any design pattern in your code ?
Design patterns are tried and tested way to solve particular design issues by various programmers in the world. Design patterns are extension of code reuse.
2. Can you name few design patterns used in standard JDK library?
Decorator design pattern which is used in various Java IO classes, Singleton pattern which is used in Runtime , Calendar and various other classes, Factory pattern which is used along with various Immutable classes likes Boolean e.g. Boolean.valueOf and Observer pattern which is used in Swing and many event listener frameworks.
3. What is Singleton design pattern in Java ? write code for thread-safe singleton in Java
Singleton pattern focus on sharing of expensive object in whole system. Only one instance of a particular class is maintained in whole application which is shared by all modules. Java.lang.Runtime is a classical example of Singleton design pattern. You can also see my post 10 questions on Singleton pattern in Java for more questions and discussion. From Java 5 onwards you can use enum to thread-safe singleton.
4. What is main benefit of using factory pattern ? Where do you use it?
Factory pattern’s main benefit is increased level of encapsulation while creating objects. If you use Factory to create object you can later replace original implementation of Products or classes with more advanced and high performance implementation without any change on client layer. See my post on Factory pattern for more detailed explanation and benefits.
5. What is observer design pattern in Java
Observer design pattern is based on communicating changes in state of object to observers so that they can take there action. Simple example is a weather system where change in weather must be reflected in Views to show to public. Here weather object is Subject while different views are Observers. Look on this article for complete example of Observer pattern in Java.
6. Give example of decorator design pattern in Java ? Does it operate on object level or class level ?
Decorator pattern enhances capability of individual object. Java IO uses decorator pattern extensively and classical example is Buffered classes like BufferedReader and BufferedWriter which enhances Reader and Writer objects to perform Buffer level reading and writing for improved performance. Read more on Decorator design pattern and Java
7. What is MVC design pattern ? Give one example of MVC design pattern ?
8. What is FrontController design pattern in Java ? Give an example of front controller pattern ?
9. What is Chain of Responsibility design pattern ?
10.What is Adapter design pattern ? Give examples of adapter design pattern in Java?
 These are left for your exercise, try finding out answers of these design pattern questions as part of your preparation.
These were some of the design pattern questions I have seen in most of interviews, there are many more specially in software design which is important in google interviews and various other companies like Amazon, Microsoft etc. Please share if you have faced any interesting design questions which is worth sharing.

Read more: http://javarevisited.blogspot.com/2012/06/20-design-pattern-and-software-design.html#ixzz3BKNi7ZTg