Friday, December 8, 2017

Usefull Git Commands

# Revert changes to modified files.
git reset --hard


# Remove all untracked files and directories. (`-f` is `force`, `-d` is `remove directories`)
git clean -fd

Tuesday, December 5, 2017

How to Clear Form Content in modal, while close

$('#mymodalname').on('hidden.bs.modal', function () {
$(this)
    .find("input,textarea,select")
       .val('')
       .end()
    .find("input[type=checkbox], input[type=radio]")
       .prop("checked", "")
       .end();

})
</script>

Tuesday, September 26, 2017

Laravel Routes

Hello Developers,

Laravel 5 Implemented routes as sepeately, previously we have in app/Http/routes.php in Laravel 4.

In Laravel 5 maintaining separate directory.

In the newer version, Laravel 5.3, we have a folder named 'routes', where we can find the following files:
  • api.php
  • console.php
  • web.php
For this new version, the routes for your controllers, you can put inside web.php file

Detailed Information:

There is
  1. routes/web.php : routes file which works similar to routes.php file where you can have your routes and all the POST routes in web.php file will be validated for the CSRF Token similar to normal Laravel Post route.
  2. routes/api.php : routes file where you can have your Application's API routes, the URL will be example.com/api/ Eg. If you have route getUsers then the API URL will be example.com/api/getUsers. The most important thing to notice is POST requests to an API url will not be validated for CSRF Token.
  3. routes/console.php : routes file where you can define your Artisan commands which you can run from Laravel Artisan CLI.


Tuesday, September 5, 2017

Codeigniter Hooks

Hook Points

The following is a list of available hook points.
  • pre_system Called very early during system execution. Only the benchmark and hooks class have been loaded at this point. No routing or other processes have happened.
  • pre_controller Called immediately prior to any of your controllers being called. All base classes, routing, and security checks have been done.
  • post_controller_constructor Called immediately after your controller is instantiated, but prior to any method calls happening.
  • post_controller Called immediately after your controller is fully executed.
  • display_override Overrides the _display() method, used to send the finalized page to the web browser at the end of system execution. This permits you to use your own display methodology. Note that you will need to reference the CI superobject with $this->CI =& get_instance() and then the finalized data will be available by calling $this->CI->output->get_output().
  • cache_override Enables you to call your own method instead of the _display_cache() method in the Output Library. This permits you to use your own cache display mechanism.
  • post_system Called after the final rendered page is sent to the browser, at the end of system execution after the finalized data is sent to the browser.

Thursday, July 27, 2017

Friday, April 21, 2017

Drupal 7 SQL cheat sheet

I'm currently developing a new Drupal 7 application (technically built as a new Drupal module), and as I'm building the application, I've made notes on database queries I've made.
The approach I'm taking is to use the following Drupal SQL query functions. As you can see from the function names, there are now different Drupal functions for each query type:
  • SELECT - use db_query
  • INSERT - use db_insert
  • UPDATE - use db_update
  • DELETE - use db_delete
Note that you can also execute some of these queries with the drupal_write_record function, but I've been having problems getting that to work, so I'm using these functions instead.
Given that background, here is my Drupal 7 SQL cheat sheet, with SQL SELECT, INSERT, UPDATE, and DELETE examples.

Drupal 7 SQL SELECT example - one row returned

Here's one way to execute a Drupal 7 SQL SELECT statement with the db_query function:
$q = "SELECT * FROM {projects} WHERE id = :id AND user_id = :uid";
$project = db_query($q, array(':id' => $id, ':uid' => $uid))
           ->fetchObject();

# returns an object with fields corresponding to the names
# of your database table, which you access like
# $project->name, $project->description, and so on.
Because I'm limiting this query by the 'id' field, I know I'm only going to get one record back. (In fact it may fail to find any records, but I'm trying to keep this simple.)
As a better example of how db_query() returns an object, here's another example:
# make sure the user owns the project id
$q = "SELECT user_id FROM {projects} WHERE id = :project_id";
$result = db_query($q, array(':project_id' => $project_id))->fetchObject();
echo 'user_id is ' . $result->user_id;
As you can see, I treat $result as an object after the query, knowing that it will have a field named user_id, because that's the name of the database table field I'm asking for in my query.

Drupal 7 SQL SELECT example - multiple rows returned

Here's how you issue a Drupal 7 SQL SELECT query with db_query and handle the results when you are expecting many rows to be returned:
$q = "SELECT * FROM {projects} WHERE uid = :uid";
$result = db_query($q, array(':uid' => $uid));
foreach ($result as $row) {
  // loop through your result set, working with $row here
}

Drupal 7 SQL INSERT with db_insert

How to execute a SQL INSERT with db_insert:
$id = db_insert('projects')
    ->fields(array(
        'user_id' => $uid,
        'project_type' => $project_type,
        'name' => $name,
        'description' => $description,
        'last_updated' => $timestamp,
        'date_created' => $timestamp
    ))
    ->execute();
With a SQL INSERT like this, the db_insert function returns the value of the SERIAL (auto_increment) field, which is very nice.

Drupal 7 SQL UPDATE with db_update

How to execute a Drupal 7 SQL UPDATE with db_update:
db_update('projects')
 ->fields(array(
         'project_count_type' => $project_count_type,
         'name' => $name,
         'description' => $description,
         'last_updated' => $timestamp,
         )
 )
 ->condition('id', $id)
 ->execute();

Drupal 7 SQL DELETE with db_delete

How to execute a Drupal 7 SQL DELETE with db_delete:
db_delete('projects')
  ->condition('id', $id)
  ->execute();

Drupal 7 SQL cheat sheet - Summary

As you have seen, you use these Drupal 7 functions for the corresponding query types:
  • SELECT - use db_query
  • INSERT - use db_insert
  • UPDATE - use db_update
  • DELETE - use db_delete
I hope these Drupal 7 SQL query examples have been helpful. I'll try to keep updating this cheat sheet as I learn more.

Thursday, April 20, 2017

How to Prevent Forms from Submitting Twice when a User Reloads the Page?

A CSRF token will handle this issue for you. If you have a check on the form, the token will stop the user from submitting twice without reloading the form before, since it will be a one-time use token.
Another way to prevent people from accidentally submitting twice is to simply gray out the button with javascript once the user clicks on it. This method is not for security reasons but rather for user experience, as it will help users understand the page is loading and they won’t have to click again to end up seeing your one-time use token error.

Thursday, April 13, 2017

The Update: 10 Most Critical Drupal Security Risks on Drupal 8

The 10 most critical Drupal security risks:
  1. SQL Injection
  2. Cross Site Scripting (XSS)
  3. Authentications and sessions
  4. Insecure direct object references
  5. Cross Site Request Forgery (CSRF)
  6. Security misconfiguration
  7. Insecure cryptographic storage
  8. Failure to restrict URL access
  9. Insufficient transport protection
  10. Unvalidated redirects

1. SQL Injection
You shouldn't use data that you don't trust (as a feed, a user input, another database, etc) directly in a database query without escaping it. This has been possible in Drupal 7 using functions that are now deprecated in Drupal 8.
db_query('SELECT foo FROM {table} t WHERE t.name = '. $_GET['user']);
Even though deprecated functions in Drupal 8 are available for us to use, we should be avoiding them. They are included only to allow legacy code to work more easily on Drupal 8.
Instead you should use the Drupal 8 object oriented method of building a query. In the example below, the $name variable will be sanitised, but there won’t be any user access permissions checked automatically.
$query = $connection->select('table', 't') ->fields('t', array('foo')) ->condition('t.name, $name);
If you need to include dynamic table names in your query, you should use escapeTable()

2. Cross Site Scripting (XSS)
XSS enables attackers to inject client-side scripts into web pages in order to carry out malicious actions. A large proportion of security vulnerabilities on web applications are XSS, so it makes sense to understand them and avoid them.
You should always escape the variables you send to the output if they come from a non trusted source, like the parameters of a URL. For example, this code is insecure:
print $_GET['id'];
It's also very common to see code like this, specially in custom themes:
$output .= $node->title;
The problem in the code above is that Drupal doesn't usually filter the user input when a node is saved. So the user could save malicious code in the title and then it will be printed without any kind of filtering.
One more obvious mistake is giving full HTML permissions to users who aren’t trusted, or allowing use of unsafe tags as <script>.
So, what can you do?
Luckily, the Twig templating engine that Drupal 8 uses now sanitises all variables by default. Ideally, all your HTML output should be from Twig templates.
Drupal also includes other API functions that you should use where appropriate. The Drupal 8 security documentation recommends the following functions:
  • Use t() and \Drupal::translation()->formatPlural() with @ or % placeholders to construct safe, translatable strings.
  • Use Html::escape() for plain text.
  • Use Xss::filter() for text that should allow some HTML tags.
  • Use Xss::filterAdmin() for text entered by a admin users that should allow most HTML.
  • Use Drupal.t() , Drupal.formatPlural() in JavaScript.

3. Authentications and sessions
You need to deal with these issues:
  • Weak password storage and account management
  • Session hijacking / fixation
  • Lack of session timeout / logout
Luckily, Drupal has good solutions for these built in.
  • Like Drupal 7, Drupal 8 stores passwords in the database in hashed form. This means that anyone who gets access to the database does not get access to user’s passwords.
  • In Drupal 8, the user’s session data is also stored in the database in hashed form. This means sessions can’t be hijacked by anyone with access to the database.

4. Insecure direct object references
It’s possible to load a node without checking that the user has access to it. For example, this will load the node a node with a certain id:
$node = \Drupal\node\Entity\Node::load($nid);
The Drupal 8 approach is to use $node->access($operation) to determine if the user has permission to perform a particular operation on the node.
When using Views, sometimes we don't make sure the user has access to nodes. One common issue is forget to add "published = Yes" to the view filters.

5. Cross Site Request Forgery (CSRF)
Below is an example of an image tag that could be added by any user who has permission to enter full HTML. When a user loads the page with this tag they will be logged out.
<img src="http://example.com/user/logout" />
It would be possible to delete content in the same way:
<img src="http://example.com/node/12/delete" />
However, in this case Drupal always asks "Are you sure you want to delete...?" when you try to delete an item to mitigate the risk of this happening.
This is an illustration of why it’s important to grant the ability to use Full HTML only to your trusted users. It’s also important that we use the Drupal API to achieve what we need wherever possible. The Form API includes input validation and security features that will mitigate the risk of a CSRF attack. For example, you should always make sure that you have a confirmation form for any critical custom operations (such as deleting content) so that nothing bad can happen if it’s linked to directly.

6. Security misconfiguration
Secure server
  • Make sure that your file permissions[https://www.drupal.org/node/244924] are appropriate to prevent unauthorised file access.
  • Control the maximum POST size and maximum file upload size by settings these in the php configuration on your server. Without this, attackers are able to upload large files or send large POST requests to use up system resources.
  • FTP is a vintage technology and was not designed to be secure. It includes a list of vulnerabilities that are well documented HERE. Use a version control system like git or at the very least SSH / SCP to get files onto your server.
  • Once you’re using SSH / SCP, consider using keys instead of passwords. This is an easier, more secure and more reliable way of signing into your server.
  • Keep your operating system up to date. Common Linux distributions will have an update system that will prompt you to do this.
  • Don’t have unnecessary applications running on a server. The more applications you have, the more software you’ll need to keep updated and the more likely it is that one of them will expose a security flaw.
Secure Drupal
  • Is your admin password strong enough? Use a password tool such as KeePass or LastPass to generate a secure password that you don’t use on any other sites and to keep track of all your passwords.
  • Double check all the "administer *" permissions and make sure they’re only assigned to trusted user roles. The "Administer text formats and filters" permission can allow a user to take control of a site.
  • Use Update module and keep track of the security news. Security updates are made on Wednesdays.

7. Insecure cryptographic storage
You may find that you develop custom modules that need to store sensitive data. There’s no native way in Drupal to do two-way encryption (i.e. to encrypt data that you’ll want to decrypt again later). If your database or a backup copy of your database is accessed, then you could be exposing sensitive data.
There’s a contributed module called Encrypt which provides an API you can use to encrypt the data you need to.
 
8. Failure to restrict URL access
If your custom module implements custom routing using Drupal 8’s new routing system, make sure that access permissions to your URLs you create are set properly. In Drupal 8, routing is done with YAML configuration. For example, the following would allow anyone who can access content on your site to access the path /example/settings.
example.name: path: '/example/settings' defaults: _controller: '\Drupal\example\Controller\ExampleController::content'requirements: _permission: 'access content'
Make sure that this is what you want and if it isn’t, check out the routing documentation to see how to achieve the access settings you need.

9. Insufficient transport protection
Tools like Wireshark allow you to analyse network traffic on the network you’re connected to. Using such a tool, a person connected to the same Wifi network as you in your office or in a coffee shop can see any unencrypted data you’re sending or receiving.
Configuring your server to allow access to your Drupal site over an HTTPS connection will allow your users to visit your site securely. You’ll require an SSL certificate that allows a user’s browser to confirm that the login page is not a forgery and it encrypts the username and password when it’s sent over the network. This prevents malicious people from stealing your login details.
 
10. Unvalidated redirects
The original security blog post contained unvalidated redirects as a separate security issue. However, we consider that this is now really a combination of the issues discussed under point 5: Cross Site Request Forgery, so won’t go into this further here.

Having covered what we consider may be the common pitfalls in Drupal 8 security, it’s important to remember that Drupal is one of the most secure content management systems available and Drupal 8 is its most secure version yet. We’d recommend you keep the points mentioned here in mind as you dive into Drupal 8. If you’ve already built one or more Drupal sites you should now have a basis for a security audit when you review your code. Above all, stay safe and stay secure!

Source: http://www.cameronandwilding.com/blog/edward/update-10-most-critical-drupal-security-risks-drupal-8

Sunday, January 22, 2017

Drupal Console commands

$ drupal list Drupal Console version 0.6.5 Available commands: cr Rebuild and clear all site caches. drush Run drush from console. help Displays help for a command list Lists commands self-update Update the console to latest version. cache cache:rebuild Rebuild and clear all site caches. config config:debug Show the current configuration. container container:debug Displays current services for an application. generate generate:command Generate commands for the console. generate:controller Generate & Register a controller generate:entity:config Generate a new "EntityConfig" generate:entity:content Generate a new "EntityContent" generate:form:config Generate a new "ConfigFormBase" generate:module Generate a module. generate:plugin:block Generate a plugin block generate:plugin:imageeffect Generate image effect plugin. generate:plugin:rest:resource Generate plugin rest resource generate:service Generate service migrate migrate:debug Display current migration available for the application migrate:execute Execute a migration available for application module module:debug Display current modules available for application module:download Install module or modules in the application module:install Install module or modules in the application module:uninstall Install module or modules in the application router router:debug Displays current routes for the application router:rebuild Rebuild routes for the application

Source : http://enzolutions.com/articles/2015/01/25/what-is-drupal-console-for-me/

Wednesday, January 18, 2017

Cross-Site Scripting (XSS)

Cross-Site Scripting (XSS) is probably the most common singular security vulnerability existing in web applications at large. It has been estimated that approximately 65% of websites are vulnerable to an XSS attack in some form, a statistic which should scare you as much as it does me.

What is Cross-Site Scripting?

XSS occurs when an attacker is capable of injecting a script, often Javascript, into the output of a web application in such a way that it is executed in the client browser. This ordinarily happens by locating a means of breaking out of a data context in HTML into a scripting context - usually by injecting new HTML, Javascript strings or CSS markup. HTML has no shortage of locations where executable Javascript can be injected and browsers have even managed to add more. The injection is sent to the web application via any means of input such as HTTP parameters.
One of the major underlying symptoms of Cross-Site Scripting’s prevelance, unique to such a serious class of security vulnerabilities, is that programmers continually underestimate its potential for damage and commonly implement defenses founded on misinformation and poor practices. This is particularly true of PHP where poor information has overshadowed all other attempts to educate programmers. In addition, because XSS examples in the wild are of the simple variety programmers are not beyond justifying a lack of defenses when it suits them. In this environment, it’s not hard to see why a 65% vulnerability rate exists.
If an attacker can inject Javascript into a web application’s output and have it executed, it allows the attacker to execute any conceivable Javascript in a user’s browser. This gives them complete control of the user experience. From the browser’s perspective, the script originated from the web application so it is automatically treated as a trusted resource.
Back in my Introduction, I noted that trusting any data not created explicitly by PHP in the current request should be considered untrusted. This sentiment extends to the browser which sits separately from your web application. The fact that the browser trusts everything it receives from the server is itself one of the root problems in Cross-Site Scripting. Fortunately, it’s a problem with an evolving solution which we’ll discuss later.
We can extend this even further to the Javascript environment a web application introduces within the browser. Client side Javascript can range from the very simple to the extremely complex, often becoming client side applications in their own right. These client side applications must be secured like any application, distrusting data received from remote sources (including the server-hosted web application itself), applying input validation, and ensuring output to the DOM is correctly escaped or sanitised.
Injected Javascript can be used to accomplish quite a lot: stealing cookie and session information, performing HTTP requests with the user’s session, redirecting users to hostile websites, accessing and manipulating client-side persistent storage, performing complex calculations and returning results to an attacker’s server, attacking the browser or installing malware, leveraging control of the user interface via the DOM to perform a UI Redress (aka Clickjacking) attack, rewriting or manipulating in-browser applications, attacking browser extensions, and the list goes on...possibly forever.

Thursday, January 5, 2017

Five 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 newdirectly, 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
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
<?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 class
If you run this code on the command line using the php interpreter, you get this result:
1
2
3
% 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
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
<?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 methods
Running the script on the command line yields the same result as the code in Listing 1, as shown here:
1
2
3
% 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
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
<?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 oneDatabaseConnection 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 singleton
The 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.
1
2
3
4
% 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
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
<?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 thatIObserver 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
If you run this on the command line, you see this output:
1
2
3
% 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
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
<?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 commands
If you run the script, which contains some test code, you see the following output:
1
2
3
4
% 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
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
<?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 users
The 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 IStrategyinterface, 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:
1
2
3
4
5
6
7
8
9
10
11
12
13
% php strategy.php
Array
(
    [0] => Jack
    [1] => Lori
    [2] => Megan
)
Array
(
    [0] => Andy
    [1] => Megan
)
%
The test code runs the same user lists against two strategies and shows the results. In the first case, the strategy looks for any name that sorts after J, so you get Jack, Lori, and Megan. The second strategy picks names randomly and yields different results every time. In this case, the results are Andy and Megan.
The strategy pattern is great for complex data-management systems or data-processing systems that need a lot of flexibility in how data is filtered, searched, or processed.

Conclusions

These are just a few of the most common design patterns used in PHP applications. Many more are demonstrated in the Design Patterns book. Don't be put off by the mystique of architecture. Patterns are great ideas you can use in any programming language and at any skill level.

SRC: https://www.ibm.com/developerworks/library/os-php-designptrns/

Difference between hook_boot and hook_init Drupal

hook_boot() hook_init() hook_boot() will executes even on cached pages hook_init() will not executes on cached pages hook_boot() is ...