Why extract () and When/When-Not to Use extract() in php

Why extract ()

Yes, we need readable code. Hire a resource who can read better.

Usually, in our code, when we use arrays as params in a function, using extract() function in php makes it very easy to parse each and every array value in a variable. It has both pros and cons which i have tried to cover in the blog. Give it a Try!

extract (PHP 4, PHP 5)

Import variables into the current symbol table from an array.

int extract ( array &$array [, int $flags = EXTR_OVERWRITE [, string $prefix = NULL ]] )

Checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table.

What is symbol Table

In computer science, a symbol table is a data structure used by a language translator such as a compiler or interpreter, where each identifier in a program’s source code is associated with information relating to its declaration or appearance in the source, such as its type, scope level and sometimes its location.

An example of symbol table has been given below:

Symbol name Type Scope
bar function, double extern
x double function parameter
foo function, double global
count int function parameter
sum double block local
i int for-loop statement

Parameters

array

An associative array. This function treats keys as variable names and values as variable values. For each key/value pair it will create a variable in the current symbol table, subject to flags and prefixparameters.

You must use an associative array; a numerically indexed array will not produce results unless you useEXTR_PREFIX_ALL or EXTR_PREFIX_INVALID.

flags

The way invalid/numeric keys and collisions are treated is determined by the extraction flags. It can be one of the following values:

EXTR_OVERWRITE
If there is a collision, overwrite the existing variable.
EXTR_SKIP
If there is a collision, don’t overwrite the existing variable.
EXTR_PREFIX_SAME
If there is a collision, prefix the variable name with prefix.
EXTR_PREFIX_ALL
Prefix all variable names with prefix.
EXTR_PREFIX_INVALID
Only prefix invalid/numeric variable names with prefix.
EXTR_IF_EXISTS
Only overwrite the variable if it already exists in the current symbol table, otherwise do nothing. This is useful for defining a list of valid variables and then extracting only those variables you have defined out of $_REQUEST, for example.
EXTR_PREFIX_IF_EXISTS
Only create prefixed variable names if the non-prefixed version of the same variable exists in the current symbol table.
EXTR_REFS
Extracts variables as references. This effectively means that the values of the imported variables are still referencing the values of the array parameter. You can use this flag on its own or combine it with any other flag by OR’ing the flags.

If flags is not specified, it is assumed to be EXTR_OVERWRITE.

prefix

Note that prefix is only required if flags is EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALIDor EXTR_PREFIX_IF_EXISTS. If the prefixed result is not a valid variable name, it is not imported into the symbol table. Prefixes are automatically separated from the array key by an underscore character.

Return Values

Returns the number of variables successfully imported into the symbol table.

Example 1

<?php
$size = "large";
$var_array = array("color" => "blue",
                   "size"  => "medium",
                   "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "prefix");

echo "$color, $size, $shape, $prefix_size\n";
?>

The above example will output:

blue, large, sphere, medium

Example 2

We have an associative array with a valid key (A Key following variable naming convention) in an array and we are using them afterwards in a function e.g.
$a = $param['a'];
$b = $param['b'];
$c = $param['c'];
$d = $param['d'];
$e = $param['e'];
$f = $param['f'];
$g = $param['g'];
$h = $param['h'];
$i = $param['i'];
$j = $param['j'];
Using extract() function, we can replace these 10 lines with 1 line.
extract($param);

When/When-Not to Use extract() in php

When-Not

Its use is very simple but we have to use it very carefully on untrusted data, like user input (i.e. $_GET, $_FILES, $_REQUEST, etc.). If you do, for example if you want to run old code that relies on register_globals temporarily, make sure you use one of the non-overwriting flags values such as EXTR_SKIP

When

We can usually use it while passing variables/arrays/input params from one function to an other. For more code readability, we can use EXTR_PREFIX_ALL flag to append a prefix with each param name to identify it uniquely similar to mention in example 1.

Using expression(), db_or(), isNull(), isNotNull() in Drupal 7.x

I have resolved an issue, where i have to concat a php variable with database field and save it to database where the value is not null. So, for resolving this issue, i have gone through some mysql function and drupal query functions which i will describe below with examples.

expression()

I have used drupal expressions to update database field according to a mysql function. e.g.


$updated = db_update('table_name')
->expression('column_name', 'CONCAT(:prepend, column_name)', array(
':prepend' => 'string to prepend ',
))
->condition('id', $id)
->execute();

OR To add an expression with the query:

$count_alias = $query->addExpression('COUNT(uid)', 'uid_count');
$count_alias = $query->addExpression('created - :offset', 'uid_count', array(':offset' => 3600));

You can see the details here: https://www.drupal.org/node/1848358 https://api.drupal.org/api/drupal/includes!database!query.inc/function/UpdateQuery%3A%3Aexpression/7

db_or()

Returns a new DatabaseCondition, set to “OR” all conditions together. An example of usage can be seen here.

$or = db_or()->condition('tid1', 5)->condition('tid2', 6);
db_delete('term_relation')->condition($or)->execute();

You can see the details here: https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_or/7

isNull(), isNotNull()

To filter a database field on whether the value is or is not NULL, use the following methods:

$query->isNull('myfield');
// Results in (myfield IS NULL)

$query->isNotNull('myfield');
// Results in (myfield IS NOT NULL)

Things to Know While Writing .install files (Drupal 7.x) – Part 1

.install file is run the first time a module is enabled, and is used to run setup procedures as required by the module. The most common task is creating database tables and fields. The .install file does not have any special syntax. It is merely a PHP file with a different extension..install files are also used to perform updates when a new version of a module needs it.

_install Function ()

Install instructions are enclosed in a _install() function. Database tables are created using the Schema API

As an example, here is an excerpt of the schema definition for Drupal’s ‘node’ table:

<!--?php
 $schema['node'] = array(
    'description' => t('The base table for nodes.'),
    'fields' => array(
      'nid' => array(
        'description' => t('The primary identifier for a node.'),
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE),
      'vid' => array(
        'description' => t('The current {node_revisions}.vid version identifier.'),
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0),
      'type' => array(
        'description' => t('The {node_type} of this node.'),
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => ''),
      'title' => array(
        'description' => t('The title of this node, always treated a non-markup plain text.'),
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => ''),
      ),
    'indexes' => array(
      'node_changed'        => array('changed'),
      'node_created'        => array('created'),
      ),
    'unique keys' => array(
      'nid_vid' => array('nid', 'vid'),
      'vid'     => array('vid')
      ),
    'primary key' => array('nid'),
    );
?>

Module updates using hook_update_N:

Updating your module, for example updating your schema, can be done using hook_update_N functions. The API page for this is at: function hook_update_N. e.g.

<?php
function mymodule_update_1() {
  $ret = array();
  db_add_field($ret, 'mytable1', 'newcol', array('type' => 'int'));
  return $ret;
}
?>

Important Points to Consider before Writing Updates:

  • Drupal update core allow only numerics as valid update numbers. so Drupal will not pick 21123-dasdador vvv2123 etc. as an update number.
  • Every Consecutive update number should be greater than previous update number e.g. hook_update_21() will be followed by hook_update_20() and if you write hook_update_19() after executing hook_update_21() then drupal will not consider that update.
  • Please don’t write update hook when you enable module first time. Because enabling module first time will only execute install function and will just update the update number to provided maximum update number without executing them. e.g. you have enabled a module which includes install() as well as hook_update_N but after enabling module when you will execute update.php, it will not show your updates.

Lets Start Development using Laravel

Introduction

  • Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as authentication, routing, sessions, and caching.
  • Laravel is combination of best things in other web frameworks, including frameworks implemented in other languages, such as Ruby on Rails, ASP.NET MVC, and Sinatra.
  • Laravel helps the developers to build a fantastic web application without sacrificing the quality in an elegant way.
  • Code Happy by Daylerees is a useful book written by a code developer.

http://laravel.com/docs?%2Fdocs%2F Installation

Configuration

  • Setting up encryption key for app. This key is stored in file laravel/app/config/app.php
  • In terminal type following command this will update the key in mentioned file.
    $ php artisan key:generate 
  • One useful thing that may help to access the laravel files with http://localhost:8000. For this purpose edit the app.php file and input the Application url up-to public directory .
    File:-- /var/www/laravel/app/config/app.php
    return array(
    // Other parameters as settings required
           url => 'http://localhost/laravel/public/' ,
    
    );
  • Other useful artisan commands can be seen at http://laravel.com/docs/artisan.
  • For setting up database go to /var/www/laravel/app/config/database.php and update the database in this file.
  • Clear the cache from browser and refresh the page.

Hello World

  • open the file app/routes.php and add the text
     Route::get('/helloworld', function()
    {
        return View::make('helloworld');   // Here helloworld will find the file app/views/helloworld.php 
    });
  • Create a file app/view/helloworld.php and put the HTML code here. This will be rendered when user will hit the url http://localhost/laravel/public/helloworld
  • If file is in sub direcory to view then simply use subdirnane.filename instead using subdir/filename in View::make(‘subdirnane.filename’).

Clean Url

  • In some case we have to apend /index.php/ in url . Then enable the clean url by visiting the suggestion given at following links.

http://stackoverflow.com/questions/12448912/apache-mod-rewrite-for-laravel https://mathiasbynens.be/notes/apache-allowoverride-all http://www.mediawiki.org/wiki/Thread:Manual_talk:Short_URL/Apache/AllowOverride_All Passing Variables to views

  • For this purpose simply create a variable in Route function and pass it to view
     $greeting = "Hi ";
        return View::make('helloworld')->with("greeting",$greeting);
  • The $greeting will now be available in helloworld.php in view directory.
  • Passing Multiple parameters
    • This is possible to pass an array to with method with keys as variable name and value as variable value.
    • We can also pass variable to the views by passing the second parameter to make(). This approach gives clean and neat code.
      Route::get('/helloworld', function() {
        $data = array(
          "greeting" => "Hello",
          "thing" => "World" 
        );
        return View::make('helloworld', $data);
      });

Using Blades

  • If we change the extension of file to helloworld.blade.php then we can get the most advanced feature by the Blades.
  • {{Any php expression will be evaluated and output will be shown to file in .blade.php file }}
  • Foreach loop
 @foreach($items as $item)
        {{ $item }}
 @endforeach
  • If statement
    @if()
         action ;
    @endif
  • Forelse loop is useful because if there are items the foreach loop will be executed and if there is no item then forelse loop will be executed.
     : -- view/master.blade.php
    @forelse($items as $item)
         {{ $item }}
    @empty
         There is no item.
    @endforelse

Layouts

  • Create a master file and define the areas with @yield(“areaname”) which will be filled out by derived file.
File : -- view/master.blade.php
<html>
    <head>
    </head>
    <body>
               <div class="container">
                            @yield("content") //This is a variable that will be populated from derived file
               </div>
    </body>
</html>
File : -- view/index.blade.php
@layout("master")

@section("content")
 This is content to be displayed in place of @yield("content")
@endsection
  • If we need to get some items such as nav items in the parent and child
File :-- view/master.blade.php
    <nav>
       @section("nav")
           <li>Home</li>
           <li>About</li>
       @yield_section
    </nav>
File:-- view/index.blade.php
@section("nav")
    @parent  // For parent links like *Home* and *About*
     <li> Appended item </li>
@endsection

Code Generator

Databases

  • Raw Queries
    • These are plain SQL queries that we run in the framework of Laravel
       $result = DB::query("Select * from tableName");
       $firstRowWithoutLimit = DB::first("Select * from tableName"); 
       $title = DB::only("Select title from tableName"); // For returning specific field not whole object
      return $title; 
       $insert =  DB::query("Insert into tablename(col1,col2) values(:VarName1 , :VarName2) , array($VarName1 , $VarName2)");
       $insert =  DB::query("Insert into tablename(col1,col2) values(? , ?) , array($VarName1 , $VarName2)");
  • Fluent Query Builder
    • Useful queries can be found at http://laravel.com/docs/queries . Developer can customize these queries as per requirements.
    • Some examples are as below
       $results = DB::table("tableName")->where("column","operator",value)->get();
       // operator contains all valid operators like '=' , '!=' etc
       $title = DB::table("tableName")->where("column","operator",value)->only("title");
       // Get the title field only
       $title = DB::table("tableName")->get(array("title"));
       $title = DB::table("tableName")->get(array("title as heading")); // Use of alias
       
      $post = DB::table("tableName")
                                   ->where("id","!=",1)
                                   ->or_where("title","=",'Title')
                                   ->get();
      $post = DB::table("tableName")
                                   ->where_id_and_title(1,"title")  // Dynamic methods and by Laravel
                                   // ->where_id_or_title(1,"title")  // Dynamic methods ORing by Laravel
                                   ->get();
  • Object Relational Model ORM Eloquent
    • For this purpose we need to create a class with the same name as the db table name for storage.
      File :-- models/User.php
      class Users extends Eloquent{}
    • Then Eloquent methods will be available with class User.
    • When creating table there should be two columns created_at and updated_at or change the value of public $timestamps = false; in Model class.
  • Migrations
    • For crating a new migration simply run the following command,
       php artisan migreate:make name_the_migration
    • Schema Builder class helps to create new schema ( table ) in the database. Related documentation is available here http://laravel.com/docs/schema.
       
      Schema::create('table_name',function($tabl php artisan migreate:make name_the_migratie){
                    $table->increment("id");
                    $table->string("name");
                    $table->timestamps(); // will create the updated_at and created_at field in table.
            }
      );
    • After this run the following command it will create the schema
       php artisan migrate 

Controllers

  • Create the controller file
  • Register the controller in route.php file.
  • For automatic detection of all controllers simply code the following line.
    File : -- routes.php
    <?php 
          Route::controller(controller::detect());
    ?>
  • Naming routes can be created , documentation is available here. http://laravel.com/docs/routing#named-routes
  • Nested controllers can also be created , the convention to follow is change the name of class to all path from controller (replace directory slashes with underscores ). Suppose if file is controllers > admin > Prefrences.php then file class name will be as follows
File : -- Controllers/admin/Prefrences.php
class Admin_Prefrences_Controller extends Base_Controller{

}

Authentication

  • File is app/auth.php responsible for authentication. There is mapping of the fields .
  • Auth::attempt($credentials) method takes password without hashed. So not to hash the input taken from the form (Laravel takes care at its own side).
  • Auth::check() checks whether the session is implemented ?
  • Auth::logout() is used to logout the user and clears his session.
  • Auth::guest() is used to check the whether it is logged in user or guest user .

Relationships