Wednesday, December 9

SASS vs LESS

Why Sass is better than LESS

    Sass lets you write re-usable methods and use logic statements; ie. conditionals and loops. LESS can do these things but in an inefficient and counter-intuitive way (ie. guarded mixins for conditionals, self-referencing recursion for loops). Like Less, Sass comes with lots of very handy functions built-in including colour manipulation, mathematics, and parameter lists.
    Sass users can utilise the awesome power of the Compass library. There are libraries available to Less users, but nothing really comes close to Compass, which is regularly maintained and contributed to by a huge community. Compass has some really awesome features like dynamic sprite-map generation, legacy browser hacks, and cross-browser support for CSS3 features.
    Compass also lets you add an external framework like Blueprint, Foundation, or Bootstrap on top. This means you can easily harness all the power of your favourite framework without having to deal with the mess of using multiple tools.

Problems with Less

Less aims to be as much like CSS in style, syntax and structure, and while this is a nice thought for easing users into writing it, there are a few issues which make it a lot less fun to work with than Sass:
Logic statements

In Less you can write a basic logic statement using a ‘guarded mixin':
<style>
    .lightswitch(@colour) when (lightness(@colour) > 40%) {
      color: @colour;
      background-color: #000;
      .box-shadow(0 3px 4px #ddd);
    }
    .lightswitch(@colour) when (lightness(@colour) < 41%) {
      color: @colour;
      background-color: #fff;
      .box-shadow(0 1px 1px rgba(0,0,0,0.3));
    }
</style>

The equivalent in Sass using if statements:

<style>
    @mixin lightswitch($colour) {
      color: $colour;
      @if(lightness($colour) > 40%) {
        background-color: #000;
        @include box-shadow(0 3px 4px #ddd);
      }
      @if(lightness($colour) <= 40%) {
        background-color: #fff;
        @include box-shadow(0 1px 1px rgba(#000,0.3));
      }
    }
</style>

Loops

In Less you can loop through numeric values using recursive functions:

<style>
    .looper (@i) when (@i > 0) {
      .image-class-@{i} {
        background: url("../img/@{i}.png") no-repeat;
      }
   
      .looper(@i - 1);
    }
   
    .looper(0);
   
    .looper(3);
    //--------------- Outputs: --------------------
    //.image-class-3 {
    //  background: url("../img/3.png") no-repeat;
    //}
    //.image-class-2 {
    //  background: url("../img/2.png") no-repeat;
    //}
    //.image-class-1 {
    //  background: url("../img/1.png") no-repeat;
    //}
</style>

In Sass you can iterate through any kind of data, which is much more helpful:

<style>
    @each $beer in stout, pilsner, lager {
      .#{$beer}-background {
        background: url("../img/beers/#{$beer}.png") no-repeat;
      }
    }
    // ------------------- Outputs: ---------------------
    //.stout-background {
    //  background: url("../img/beers/stout.png") no-repeat;
    //}
    //.pilsner-background {
    //  background: url("../img/beers/pilsner.png") no-repeat;
    //}
    //.lager-background {
    //  background: url("../img/beers/lager.png") no-repeat;
    //}
</style>

Custom functions

In Sass, you can write your own handy functions like so:

<style>
    //Courtesy of Foundation...
    $em-base: 16px !default;
    @function emCalc($pxWidth) {
      @return $pxWidth / $em-base * 1em;
    }
   
    In Less:
   
    @em-base: 16px;
    .emCalc(@pxWidth) {
      //Ah. Crap...
    }
</style>

Hmmm… Which would you rather use?
Problems getting started with Sass and Compass

It seems like the biggest problems that folks have with moving to Sass are:

    The added hassle of setting up the Ruby environment
    Crippling fear of the command line
    The inconvenience and time involved switching to a different tool

We’ve written a tutorial for beginners eager to make the move to Sass and Compass which details every step to show just how easy and fast it is to get started, the awesome power of Compass, and how similar writing Sass is to other technologies.

If you’re already a Sass addict, take a look at our post about the problems with pre-processed CSS and the future of web presentation.

With the enormous popularity of Twitter’s Bootstrap, many designers and developers are moving toward this framework to fulfil their presentational needs. I’ve seen quite a few developers grumpy about the fact that it is built with Less. As mentioned in another article, There are several forks of Bootstrap (like this one) which let developers customise their favourite framework in their favourite pre-processor language.
Want to get started with Sass and Compass?

Check out our 20 minute Sass and Compass tutorial for absolute beginners!

We hope you've enjoyed reading this article. Why not sign up to our newsletter to receive regular updates on our latest projects, research, and other news in the world of technology, web design and development.

Wednesday, August 26

Difference between PHP4 and PHP5

There are some 27 differences which I got to  know between PHP4 and PHP5:

    1. PHP5 removed register_globals, magic quotes, and safe mode. This was due to the fact that register_globals had opened security holes by intentionally allowing runtime data injection and the use of magic quotes had an unpredictable nature.
   
    2. PHP4 was powered by Zend Engine 1.0, while PHP5 was powered by Zend Engine II.
   
    3. PHP5 replaced magic quotes with the addslashes() function in order to escape characters.
   
    4. PHP4 is more of a procedure language while PHP5 is object oriented.
   
    5. In PHP5 one can declare a class as Abstract.
   
    6. PHP5 incorporates static methods and properties.
   
    7. PHP5 introduces a special function called __autoload()
   
    8. PHP5 allows one to declare a class or method as Final
   
    9. PHP5 introduces a number of magic methods, such as __call, __get, __set and __toString
   
    10. In PHP5, there are 3 levels of visibilities: Public, private and protected.
   
    11. PHP5 introduced exceptions.
   
    12. In PHP4, everything was passed by value, including objects. Whereas in PHP5, all objects are passed by reference.
   
    13. PHP5 introduces interfaces. All the methods defined in an interface must be public.
   
    14. PHP5 introduces new error level defined as 'E_STRICT'
   
    15. PHP5 introduces new default extensions such as SimpleXML, DOM and XSL, PDO, and Hash.
   
    16. PHP5 introduces new functions.
   
    17. PHP5 introduces some new reserved keywords.
   
    18. PHP5 includes additional OOP concepts than php4, like access specifiers , inheritance etc.
   
    19. PHP5 includes improved support of current content management systems.
   
    20. PHP5 includes reduced consumption of RAM.
   
    21. PHP5 introduces increased security against exploitation of vulnerabilities in PHP scripts.
   
    22. PHP5 introduces easier programming through new functions and extensions.
   
    23. PHP5 introduces a new MySQL extension named MySQLi for developers using MySQL 4.1 and later.
   
    24. In PHP5, SQLite has been bundled with PHP.
   
    25. PHP5 introduces a brand new built-in SOAP extension for interoperability with Web Services.
   
    26. PHP5 introduces a new SimpleXML extension for easily accessing and manipulating XML as PHP objects. It can also interface with the DOM extension and vice-versa.
   
    27. In PHP5, streams have been greatly improved, including the ability to access low-level socket operations on streams.

PHP4 vs PHP5 (Additional Features of PHP5)

Constructors and Destructors

    In PHP4, Constructor have same name as the Class name.
    In PHP5, name Constructors as _construct and Destructors as _destruct().

Passed by References

    In PHP4, everything was passed by value.
    In PHP5, all objects are passed by references.

Abstract

    In PHP5, we can declare a class as abstract.

Static Methods and Properties

    In PHP5, Static Methods and Properties are also available. When you declare a class as static, then you can access using :: operator without creating an instances of class

_autoload()

    PHP5 introduces a special function called _autoload().

Final

    PHP5 allows you to declare a class or method as final.

Magic Methods

    PHP5 introduces magic methods such as _call, _get, _set and _tostring

Visibility

    PHP5 has 3 level of visibilities
    Public: methods are accessible to everyone including objects outside the class
    Private: methods are accessible to the class itself
    Protected: methods are accessible to the class itself and inherited classes.

Exception

    PHP5 introduces exceptions handling.

Interfaces

    PHP5 introduces Interfaces.

E-Strict Error Level

    PHP5 introduces new error level defined as E_STRICT.
    E_STRICT will notify you when you use depreciated code.

Extensions

    PHP5 introduces new default extensions.
    Simple XML
    DOM and XSL
    PDO
    Hash

Sunday, August 2

jQuery for Validate Forms.

Validetta

Using callback functions
onValid() and onError()

Warning!
    To show error messages healthy, each field must be wrapped by an element like <div>

<div id="alert"></div>
<form id="exm" method="POST" action="#">
    <div>
        <label>Required, Email :</label>
        <input type="text" name="name" data-validetta="required,minLength[2],maxLength[3]">
    </div>
    <div>
        <label>Email :</label>
        <input type="text" name="email" data-validetta="required,email">
    </div>
    <button type="submit">Submit</button>
    <button type="reset">Reset</button>
</form>

<script>
    (function($){
        $('#exm').validetta({
            onValid : function( event ) {
                event.preventDefault();
                $('#alert').empty()
                    .append('<div class="alert alert-success">Nice, Form is valid</div>');
            },
            onError : function( event ){
                $('#alert').empty()
                    .append('<div class="alert alert-danger">Stop bro !! There are some errors.</div>');
            }
        }); 
    });
</script>


Plugin Download

Sunday, July 26

What's New in PHP 7.


   For all the businessmen, who are using PHP, 2015 has been an important as after eleven years, its 5.0 release that is finally coming our way. The all new major version of PHP is all set for release before the end of the year. PHP 7 is bringing a lot of new language features and an amazing performance boost.

However do you know how this will impact on your current PHP codebase? How safe it is to update? And what are the points that changed? Let’s have a look at PHP 7 and find what’s to come with it:

Performance Enhancements –



Unquestionably, performance is one of the major points why you should upgrade your servers as soon as a stable version is released.

Phpang RFC has introduced the core refactoring, which makes PHP 7 as quick as HHVM. The official level is extremely impressive – a lot of actual world apps are running on PHP 5.6 will run at least twice as instant on PHP 7.

For thorough performance level, you can give a look at Rasmus Lerdorf’s presentation at PHP Australia. Below, you can find WordPress benchmarks from that presentation:

The best thing about PHP 7 is that it handles more than twice as a lot of requests per second that in realistic terms will show a 100% enhancement on performance for WordPress sites.

Backwards Compatibility Drawbacks –

Can we have a look at the few things that potentially break a heritage application running on older versions of PHP?

    Deprecated Items Removed

There are a lot of deplored items, which have been removed as they have been deprecated for some time now and expectantly you are not using them. However, this might have a huge impact on legacy applications. Particularly, ASP-style tags like (<%; <%= and %>) were removed along with script tags (<script language="php">).

You should ensure that you are using the optional <?php tag instead. There are various other functions as well that were earlier deprecated such as split have also been detached in PHP 7.

When it comes to talking about ereg extension, it has been deprecated since PHP 5.3. It is must that it replaced with the PCRE extension (preg_* functions) that provides a lot of features. You can also make use of the mysqli extension and the mysqli_* functions instead for a direct migration.

Uniform Changeable Syntax –

At the time of evaluating variable expressions, the uniform variable syntax is mainly meant to solve a series of discrepancy. You can consider the below mentioned code:

<?php
class Person
{
    public $name = 'Erika';
    public $job = 'Developer Advocate';
}
    $person = new Person();
    $property = [ 'first' => 'name', 'second' => 'info' ];
    echo "\nMy name is " . $person->$property['first'] . "\n\n";
?>

The expression $person->$property[‘first’] is estimated as $ person->{$property['first']} in PHP 5. It will be understand as $person->name, providing you the result “My name is Erika” in practical terms. It shows clear inconsistencies with the normal expression evaluation order that is left to right even if it is an edge case.

However, an instant way to fix this issue is by openly defining the evaluation order with the help of curly braces that will give guarantee the same behavior on both PHP 5 and PHP 7.
All credit goes to the new uniform left-to-right variable syntax as there are lots of expressions earlier treated as unacceptable will now become valid. Consider the following class in order to illustrate this new behavior:

<?php
class Person
{
    public static $company = 'DigitalOcean';
    public function getFriends()
    {
        return [
            'erika' => function () {
                return 'Elephpants and Cats';
            },
            'sammy' => function () {
                return 'Sharks and Penguins';
            }
        ];
    }
    public function getFriendsOf($someone)
    {
        return $this->getFriends()[$someone];
    }
    public static function getNewPerson()
    {
        return new Person();
    }
}
?>

We are also capable of developing nested associations and different combinations between operators:

<?php
    $person = new Person();
    echo "\n" . $person->getFriends()['erika']() . "\n\n";
    echo "\n" . $person->getFriendsOf('sammy')() . "\n\n";
?>

This clip will give us a parse error on PHP 5, but works as expected on PHP 7.

Similarly, nested static access is also possible:

<?php
    echo "\n" . $person::getNewPerson()::$company . "\n\n";
?>

This would provide us the classic T_PAAMAYIM_ NEKUDOTAYIM syntax error in PHP 5.

Incurable Error With Multiple "Default" Clauses

Again, it is a border case and it is more about logic errors in your code. There is no use for multiple default clauses in a switch; however, it never caused any problem. It can be quite difficult to detect the mistake. The last default would be used in PHP 5, but when it comes to PHP 7, one will not get a Fatal Error: Switch statements may also contain one default clause.

New Language Features

Now, here is the best part – Let's have a look at the most amazing features, which will be obtainable when you upgrade to PHP 7.

New Operators –

The all new PHP 7 comes with two shiny new operators: the spaceship and the null coalesce operator. The spacecraft operator (<=>) that is also known as combined comparison operator, which can be used to make your chained comparison more concise.

Consider the following expression:
$a <=> $b

Above mentioned expression can evaluate to -1 if $a is smaller than $b, 0 if $a equals $b, and 1 if $b is greater than $a. Basically, it is a shortcut for the following expression:

$b, 0 if $a equals $b, and 1 if $b is greater than $a.

For a common use case, the null coalesce operator (??) that also works as a shortcut for a common use case: a conditional attribution that checks if a value is set before using it. Usually, you can do something like this in PHP 5:

<?php
    $a = isset($b) ? $b : "default";
?>

With the null coalesce operator in PHP 7, we can simply use:
<?php
$a = $b ?? "default";
?>

Scalar Type Hints

The most discussed new feature is coming with PHP 7 as scalar type hints will make it possible to use integers, strings, Booleans, floats as type hints for functions and methods.

By default, scalar type hints are non-restrictive that means if you pass a float value to an integer parameter, it will just force it to int without generating any errors or warnings.

However, it is also possible to allow a strict mode, which will throw errors at the time of wrong type is passed as an argument. Have a look at the following code:
<?php
    function double(int $value)
    {
        return 2 * $value;
    }
    $a = double("5");
    var_dump($a);
?>

Return Type Hints

One major and new feature that comes with PHP 7 is the capability to define the return type of methods and functions. It performs as a same fashion as scalar type hints in spite of coercion and strict mode:

<?php
    function a() : bool
    {
        return 1;
    }
    var_dump(a());
?>

Without any warnings, this snippet will run and the returned value will be transformed to bool mechanically. In case, if you are allowing strict mode, you can get a fatal error instead:

Fatal error: Uncaught TypeError: Return value of a() must be of the type boolean, integer returned

One more time, you should notice that these errors can really be exceptions, which can be caught and handled using try/catch blocks. It is also necessary to highlight that one can make use of any valid type hint, not only scalar types.

What’s Coming Next?

The all new PHP 7’s timeline shows a steady release in mid-October. However, the company is on release candidate cycles and a beta version is already obtainable for tests.

You can check out the RFC with all the changes coming with PHP 7 for more information.

Stay connected with us to get more information on PHP 7 and its incredible new solutions that will amaze you with its performance. Moreover, you can also get in touch with our experienced PHP developer, who can give best solutions to you.


SOURCE: phpdevelopmentsolutions.blogspot.in

Friday, July 24

PHP Singleton pattern for a database class

An example of how you would implement a Singleton pattern for a database class can be seen below:

<?php
class Database implements Singleton {
    private static $instance;
    private $pdo;

    private function __construct() {
        $this->pdo = new PDO(
            "mysql:host=localhost;dbname=database",
            "user",
            "password"
        );
    }

    public static function getInstance() {
        if(self::$instance === null) {
            self::$instance = new Database();
        }
        return self::$instance->pdo;
    }
}
?>
You would make use of the class in the following manner:

<?php
$db = Database::getInstance();
// $db is now an instance of PDO
$db->prepare("SELECT ...");

// ...

$db = Database::getInstance();
// $db is the same instance as before
?>

And for reference, the Singleton interface would look like:
<?php
interface Singleton {
    public static function getInstance();
}
?>

Write a class that implements singleton pattern PHP.

In the singleton pattern a class can distribute one instance of itself to other classes.

<?php

/*
 *   Singleton classes
 */
class BookSingleton {
    private $author = 'Gamma, Helm, Johnson, and Vlissides';
    private $title  = 'Design Patterns';
    private static $book = NULL;
    private static $isLoanedOut = FALSE;

    private function __construct() {
    }

    static function borrowBook() {
      if (FALSE == self::$isLoanedOut) {
        if (NULL == self::$book) {
           self::$book = new BookSingleton();
        }
        self::$isLoanedOut = TRUE;
        return self::$book;
      } else {
        return NULL;
      }
    }

    function returnBook(BookSingleton $bookReturned) {
        self::$isLoanedOut = FALSE;
    }

    function getAuthor() {return $this->author;}

    function getTitle() {return $this->title;}

    function getAuthorAndTitle() {
      return $this->getTitle() . ' by ' . $this->getAuthor();
    }
  }

class BookBorrower {
    private $borrowedBook;
    private $haveBook = FALSE;

    function __construct() {
    }

    function getAuthorAndTitle() {
      if (TRUE == $this->haveBook) {
        return $this->borrowedBook->getAuthorAndTitle();
      } else {
        return "I don't have the book";
      }
    }

    function borrowBook() {
      $this->borrowedBook = BookSingleton::borrowBook();
      if ($this->borrowedBook == NULL) {
        $this->haveBook = FALSE;
      } else {
        $this->haveBook = TRUE;
      }
    }

    function returnBook() {
      $this->borrowedBook->returnBook($this->borrowedBook);
    }
  }

/*
 *   Initialization
 */

  writeln('BEGIN TESTING SINGLETON PATTERN');
  writeln('');

  $bookBorrower1 = new BookBorrower();
  $bookBorrower2 = new BookBorrower();

  $bookBorrower1->borrowBook();
  writeln('BookBorrower1 asked to borrow the book');
  writeln('BookBorrower1 Author and Title: ');
  writeln($bookBorrower1->getAuthorAndTitle());
  writeln('');

  $bookBorrower2->borrowBook();
  writeln('BookBorrower2 asked to borrow the book');
  writeln('BookBorrower2 Author and Title: ');
  writeln($bookBorrower2->getAuthorAndTitle());
  writeln('');

  $bookBorrower1->returnBook();
  writeln('BookBorrower1 returned the book');
  writeln('');

  $bookBorrower2->borrowBook();
  writeln('BookBorrower2 Author and Title: ');
  writeln($bookBorrower1->getAuthorAndTitle());
  writeln('');

  writeln('END TESTING SINGLETON PATTERN');

  function writeln($line_in) {
    echo $line_in.'<br/>';
  }
?>

Output

BEGIN TESTING SINGLETON PATTERN


BookBorrower1 asked to borrow the book
BookBorrower1 Author and Title:
Design Patterns by Gamma, Helm, Johnson, and Vlissides


BookBorrower2 asked to borrow the book
BookBorrower2 Author and Title:
I don't have the book


BookBorrower1 returned the book


BookBorrower2 Author and Title:
Design Patterns by Gamma, Helm, Johnson, and Vlissides


END TESTING SINGLETON PATTERN

Tuesday, July 14

Get Just The Path from a Request in PHP


It can be a little tricky to get just the path of a request in PHP.
$_SERVER['REQUEST_URI'] includes the query string.
$_SERVER['SCRIPT_NAME'] may return index.php instead of the request if you’re using a CMS like WordPress which rewrites URLs.

The most reliable method I’ve found for returning only the path without the query string uses PHP’s built in parse_url() function:

<?php

    $path_only = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

?>

Friday, June 5

Check uploaded file is actually an image using PHP.


<?php
    if (@getimagesize($_FILES["file"]["tmp_name"]) !== false) {
        $destination = "uploads/" . $_FILES["file"]["name"];
        move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
    }
?>

Monday, June 1

Remove all characters except letters and numbers.

Receiving short codes in an app via URL query strings? Instead of using complex sanitization functions, this simple RegEx replace will get rid of all the junk in the input $string except for letters and numbers:

$clean_code = preg_replace('/[^\w]/', '', $string);
 

If you want more control over which character classes are 
preserved, you can specify them explicitly:
 
 
$clean_code = preg_replace('/[^a-zA-Z0-9]/', '', $string);

Wednesday, May 20

Passing Values From JavaScript to PHP and Back

1. PHP to JavaScript

    <?php
        echo "Just wanted to say $hello";
    ?>

2. JavaScript to PHP

    <script>
        function sayHelloWorld() {
            var hello = "hello";
            var world = "world";
       
            window.location.href = "somepage.php?w1=" + hello + "&w2=" + world;
        }
    </script>
   
3. PHP Receiving and Processing The Variables

    <?php
    function sayHiBack() {
       // Check if we have parameters w1 and w2 being passed to the script through the URL
       if (isset($_GET["w1"]) && isset($_GET["w2"])) {
   
          // Put the two words together with a space in the middle to form "hello world"
          $hello = $_GET["w1"] . " " . $_GET["w2"];
   
          // Print out some JavaScript with $hello stuck in there which will put "hello world" into the javascript.
          echo "<script language='text/javascript'>function sayHiFromPHP() { alert('Just wanted to say $hello!'); }</script>";
       }
    }
    ?>

Post Multiple JavaScript Values to PHP Using jQuery AJAX

Step 1. To Package Up data for Sending

    <script>
        // Create an object using an object literal.
        var ourObj = {};
       
        // Create a string member called "data" and give it a string.
        // Also create an array of simple object literals for our object.
        ourObj.data = "Some Data Points";
        ourObj.arPoints = [{'x':1, 'y': 2},{'x': 2.3, 'y': 3.3},{'x': -1, 'y': -4}];

    </script>
   
Step 2: Transmitting This Data in jQuery AJAX

    <script>
        $.ajax({
           url: 'process-data.php',
           type: 'post',
           data: {"points" : JSON.stringify(ourObj)},
           success: function(data) {
                // Do something with data that came back.
           }
        });
    </script>
   
Step 3: Package Sent, Package Received

    <?php
    // Test if our data came through
    if (isset($_POST["points"])) {
        // Decode our JSON into PHP objects we can use
        $points = json_decode($_POST["points"]);
   
        // Access our object's data and array values.
        echo "Data is: " . $points->data . "<br>";
        echo "Point 1: " . $points->arPoints[0]->x . ", " . $points->arPoints[0]->y;
    }
    ?>

Monday, May 11

Multiple File Extensions validate using PHP.


<?php
    $valid_file_extensions = array(".jpg", ".jpeg", ".gif", ".png");
    
    $file_extension = strrchr($_FILES["file"]["name"], ".");
    
    // Check that the uploaded file is actually an image
    // and move it to the right folder if is.
    if (in_array($file_extension, $valid_file_extensions)) {
        $destination = "uploads/" . $_FILES["file"]["name"];
        move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
    }
?>

Saturday, May 9

Tabbed Navigation with CSS



Navigation on web pages is a form of list, and tabbed navigation is like a horizontal list. It's fairly easy to create horizontal tabbed navigation with CSS, but CSS 3 gives us a few more tools to make them look even nicer.

This code tutorial will take you through the HTML and CSS needed to create a CSS tabbed menu.

<!DOCTYPE html>
<html>
  <head>
  <style>
    .tablist {
      list-style:none;
      height:2em;
      padding:0;
      margin:0;
      border: none;
    }
    .tablist li {
      float:left;
      margin-right:0.13em;
    }
    .tablist li a {
      display:block;
      padding:0 1em;
      text-decoration:none;
      border:0.06em solid #000;
      border-bottom:0;
      font:bold 0.88em/2em arial,geneva,helvetica,sans-serif;
      color:#000;
      background-color:#ccc;

      /* CSS 3 elements */
      webkit-border-top-right-radius:0.50em;
      -webkit-border-top-left-radius:0.50em;
      -moz-border-radius-topright:0.50em;
      -moz-border-radius-topleft:0.50em;
      border-top-right-radius:0.50em;
      border-top-left-radius:0.50em;
    }

    .tablist li a:hover {
      background:#3cf;
      color:#fff;
      text-decoration:none;
    }
    .tablist li#current a {
      background-color: #777;
      color: #fff;
    }
    .tablist li#current a:hover {
      background: #39C;
    }
  </style>
  </head>
  <body>
    <nav>
      <ul class="tablist">
        <li><a href="#">CSS 3</a></li>
        <li id="current"><a href="#">Tabs</a></li>
        <li><a href="#">For</a></li>
        <li><a href="#">Menus</a></li>
      </ul>
    </nav>
  </body>
</html>

Thursday, April 23

Drupal 7 Bootstrap Process ( drupal_bootstrap ) - Part 2


This is the second part of my Drupal 7 Line by Line series. In the first part I walked through Drupal 7 index.php. As you recall there are only four lines of code and two function calls that display all the pages on your Drupal 7 site.
In this post I'll start walking through one of those functions: drupal_bootstrap(). If you recall from Part 1 I said this function is starts up (bootstraps) all of Drupal's mechanisms required to handle a page request. This is only part of the story and only half the truth. A more accurate description would be that it loads up only as much of Drupal's functionality a php script needs so that the php script can uses that functionality to do something.
When drupal_bootstrap is called from index.php it is passed a single argument: BOOTSTRAP_FULL. In order for index.php (a php script) to display a web page (what the script does) it needs Drupal to bootstrap all of its mechanisms (i.e. a full bootstrap).
Lets see what the phpDoc comment and function signature for drupal_bootstrap() have to say:
<?php/**
* A string describing a phase of Drupal to load. Each phase adds to the
* previous one, so invoking a later phase automatically runs the earlier
* phases too. The most important usage is that if you want to access the
* Drupal database from a script without loading anything else, you can
* include bootstrap.inc, and call drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE).
*
* @param $phase
*   A constant. Allowed values are the DRUPAL_BOOTSTRAP_* constants.
* @param $new_phase
*   A boolean, set to FALSE if calling drupal_bootstrap from inside a
*   function called from drupal_bootstrap (recursion).
* @return
*   The most recently completed phase.
*
*/
function drupal_bootstrap($phase = NULL, $new_phase = TRUE) { ?>
This basically tells us that when we call this function we have to tell it which bootstrap phase to run by passing a value to the $phase variable. The function accepts a second argument $new_phase which by default is "TRUE".

Executing drupal_bootstrap(BOOTSTRAP_FULL)

So the first thing that the function does when its run is define a static variable called $phases. That variable is assigned an array that is populated with the constants that represent the 7 phases of the bootstrap process.

<?php
 
static $phases = array(
   
DRUPAL_BOOTSTRAP_CONFIGURATION,
   
DRUPAL_BOOTSTRAP_PAGE_CACHE,
   
DRUPAL_BOOTSTRAP_DATABASE,
   
DRUPAL_BOOTSTRAP_VARIABLES,
   
DRUPAL_BOOTSTRAP_SESSION,
   
DRUPAL_BOOTSTRAP_PAGE_HEADER,
   
DRUPAL_BOOTSTRAP_LANGUAGE,
   
DRUPAL_BOOTSTRAP_FULL,
  );
?>
The function then defines two more static variables $final_phase and $stored_phase (given an initial value of -1).

<?php
 
// When not recursing, store the phase name so it's not forgotten while
  // recursing.
 
if ($new_phase) {
   
$final_phase = $phase;
  }
?>
$new_phase is TRUE by default - therefore the $final_phase is assigned the value of $phase which in this case is BOOTSTAP_FULL which has an integer value of 7.

<?php
 
if (isset($phase)) {
   
// Call a phase if it has not been called before and is below the requested
    // phase.
   
while ($phases && $phase > $stored_phase && $final_phase > $stored_phase) {?>
If $phase has a value (it does) the function enters a while loop. The conditions of the while loop are:
if the $phases array has something in it (it currently does)
AND $phase (currently BOOTSTRAP_FULL or 7)
is greater than $stored_phase (currently -1)
AND $final_phase (also currently 7)
is greater than $stored_phase (currently -1)
do stuff.
In more general terms, the function is going to keep looping until each bootstrap phase is complete and it reaches the bootstrap phase that was first passed to the function.

<?php
      $current_phase
= array_shift($phases);       // This function is re-entrant. Only update the completed phase when the
      // current call actually resulted in a progress in the bootstrap process.
     
if ($current_phase > $stored_phase) {
       
$stored_phase = $current_phase;
      }
?>
Once inside the while loop the function 'shifts off' the first value of the $phases array and assigns the value to $current_phase.
If you look back, you'll see that the first element of the $phases array was DRUPAL_BOOTSTRAP_CONFIGURATION. Therefore $current_phase gets assigned that value once the array is shifted.
After that, the function then checks if $current_phase is greater than the $stored_phase and if so assigns the value of $current_phase to $stored_phase. This is all about keeping track of what the current bootstrap phase is and what the phase was. Remember, this function is going to be looping through all the phases. In each loop drupal_bootstrap could be called again recursively.

Meat and Potatoes

We arrive at the part that actually starts doing the bootstrapping (starting up) of the individual parts of Drupal.

<?phpswitch ($current_phase) {
        case
DRUPAL_BOOTSTRAP_CONFIGURATION:
         
_drupal_bootstrap_configuration();
          break;         case
DRUPAL_BOOTSTRAP_PAGE_CACHE:
         
_drupal_bootstrap_page_cache();
          break;         case
DRUPAL_BOOTSTRAP_DATABASE:
         
_drupal_bootstrap_database();
          break;         case
DRUPAL_BOOTSTRAP_VARIABLES:
         
_drupal_bootstrap_variables();
          break;         case
DRUPAL_BOOTSTRAP_SESSION:
          require_once
DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
         
drupal_session_initialize();
          break;         case
DRUPAL_BOOTSTRAP_PAGE_HEADER:
         
_drupal_bootstrap_page_header();
          break;         case
DRUPAL_BOOTSTRAP_LANGUAGE:
         
drupal_language_initialize();
          break;         case
DRUPAL_BOOTSTRAP_FULL:
          require_once
DRUPAL_ROOT . '/includes/common.inc';
         
_drupal_bootstrap_full();
          break;
      }
?>
There is a switch/case statement that checks what the $current_phase is and then executes the code in the appropriate case.
At this stage in this line by line journey the $current_phase is DRUPAL_BOOTSTRAP_CONFIGURATION so
_drupal_bootstrap_configuration() gets called.

What happens next

Good question, but the answer will have to wait. This is a good time to stop for now since each phase in the bootstrap process requires its own post. Next time we'll take a look at _drupal_bootstrap_configuration.
While you are waiting, and if you are at all curious about the origins of the bootstrap process, you can check out http://drupal.org/node/18213 where drupal_bootstrap was born.

Drupal 7 Bootstrap Process ( drupal_bootstrap ) - Part 1



This is the beginning of what I hope will be a series of posts that take you through a Drupal 7 page load line by line.

Here is the code I dove into: index.php - as it was in the days of Drupal 4.4:
<?php// $Id: index.php,v 1.76 2003/11/25 19:26:20 dries Exp $ include_once "includes/bootstrap.inc";drupal_page_header();
include_once
"includes/common.inc"; fix_gpc_magic(); menu_build("system"); if (menu_active_handler_exists()) {
 
menu_execute_active_handler();
}
else {
 
drupal_not_found();
}
drupal_page_footer(); ?>
And that's how I became a Drupal developer. I went down the rabbit hole. I began stepping through the code (without a deubugger!) trying to sort out what it was that Drupal was doing so that I could find what I needed to change to make my site look the way I wanted to. By the time I found my answer I had learned more about Drupal than I needed or wanted to know at the time. I was also hooked.
And the rest, as they say, was history.
With the release of Drupal 7 I thought I would repeat the exercise. This time however I will document the experience to share with you. We can learn something new together.

Here is index.php - as it is today:

<?php// $Id: index.php,v 1.99 2009/10/15 14:07:25 dries Exp $ /**
* @file
* The PHP page that serves all page requests on a Drupal installation.
*
* The routines here dispatch control to the appropriate handler, which then
* prints the appropriate page.
*
* All Drupal code is released under the GNU General Public License.
* See COPYRIGHT.txt and LICENSE.txt.
*/
/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', getcwd()); require_once DRUPAL_ROOT . '/includes/bootstrap.inc';drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);menu_execute_active_handler();?>
The first thing you'll notice is that Drupal has a lot more documentation inside the code than it did 6 versions ago. This will make stepping through and explaining the code line by line a little easier (since much of the work is already done). Its worth noting that the code comments are in phpDoc format and are used to generate the code documentation found at http://api.drupal.org/
As you can see in the code comments index.php serves (nearly1) all page requests on your website. In other words, index.php is where code execution begins whether you request http://example.com/home or http://example.com/news/january/headlines or http://example.com/admin/rule/the/world.
Yes. Four (4) lines of code return every single page on your Drupal site! That's pretty amazing. So what's going on here.
A call is made to getcwd() which returns the current working directory which gets assigned to the DRUPAL_ROOT constant.
Basically Drupal is telling itself which directory in the server's file system it is installed and assigning that information to a constant that will be used elsewhere in the code.
Using that constant Drupal then includes the file bootstrap.inc from the includes directory using require_once.
<?php// $Id: bootstrap.inc,v 1.459 2010/12/30 04:35:00 webchick Exp $
/**
* @file
* Functions that need to be loaded on every Drupal request.
*/
//3000 or so more lines of code
?>
Bootstrap.inc contains roughly 80 functions that "need to be loaded on every Drupal request". As soon as bootstrap.inc gets included 37 new constants get defined.
From those 80 or so functions and 37 or so new constants only the drupal_bootstrap function is called with the value of the DRUPAL_BOOTSTRAP_FULL constant as an argument.
The short version of what is happening in this one function call is Drupal is told to start up (bootstrap) all of its mechanisms required to handle the page request. It loads configuration information, page caching system(s), database(s), session handling, translation system, modules, and everything else you can imagine (and things you might not have imagined) that are required to handle a page request.
The long version of what happens in this one function call is what many follow up posts in this series will be about. You'll have to come back for those.
Finally, the last line in index.php calls the function menu_execute_active_handler(). The short version of what this function does is to act like a telephone operator and direct or route your call to the appropriate function that can answer you.
It takes a look at the path of the requested URL (i.e. the parts after the domain name e.g. news/headlines/december) and figure out which function is responsible for handling requests for that path. Once menu_execute_active_handler() finds the function to call, it calls it. What happens at the point depends entirely on which function was called, but in most cases an html page is sent to the browser.
Once again the long version of what happens is left for another time.

Summary

And there you have it: Four lines of code and only two function calls. All you need to get a page out of Drupal. Sounds easy.
Next time I'll start looking in depth at the bootstrap process in bootstrap.inc and the drupal_bootstrap() function.
If you have any questions, suggestions or corrections just leave a comment. I truly appreciate the feedback.

Friday, April 17

Caching Data in Drupal 7

A Beginner's Guide to Caching Data in Drupal 7

Building complicated, dynamic content in Drupal is easy, but it can come at a price. A lot of the stuff that makes a site engaging can spell 'performance nightmare' under heavy load, thrashing the database to perform complex queries and expensive calculations every time a user looks at a node or loads a particular page.
One solution is to turn on page caching on Drupal's performance options administration page. That speeds things up for anonymous users by caching the output of each page, greatly reducing the number of DB queries needed when they hit the site. That doesn't help with logged in users, however: because page level caching is an all-or-nothing affair, it only works for the standardized, always-the-same view that anonymous users see when they arrive.
Eventually there comes a time when you have to dig in to your code, identify the database access hot spots, and add caching yourself. Fortunately, Drupal's built-in caching APIs and some simple guidelines can make that task easy.

The basics

The first rule of optimization and caching is this: never do something time consuming twice if you can hold onto the results and re-use them. Let's look at a simple example of that principle in action:
<?phpfunction my_module_function() {
 
$my_data = &drupal_static(__FUNCTION__);
  if (!isset(
$my_data)) {
   
// Do your expensive calculations here, and populate $my_data
    // with the correct stuff..
 
}
  return
$my_data;
}
?>

The important part to look at in this function is the variable named $my_data; we're initializing it with an odd-looking call to drupal_static(). The drupal_static() function is new to Drupal 7, and provides functions with a temporary "storage bin" for data that should stick around even after they're done executing. drupal_static() will return an empty value the first time we call it, but any changes to the variable will be preserved when the function is called again. That means that our function can check if the variable is already populated, and return it immediately without doing any more work. This pattern appears all over the place in Drupal -- including important functions like node_load(). Calling node_load() for a particular node ID requires database hits the first time, but the resulting information is kept in a static variable for the duration of the page load. That way, displaying a node once in a list, a second time in a block, and a third time in a list of related links (for example) doesn't require three full trips to the database.
In Drupal 6, these static variables were created using the PHP 'static' keyword rather than the drupal_static() function. It was also common to provide a $reset parameter on each function that used this pattern, giving modules that needed the freshest information a way to bypass the caching code. While that approach still works in Drupal 7, drupal_static() allows the process to be centralized. When modules need absolutely fresh data, they can call drupal_static_reset() to clear out any temporarily cached information.

Making it stick: Drupal's cache functions

You might notice that the static variable technique only stores data for the duration of a single page load. For even better performance, it's often possible to cache data in a more permanent fashion...
<?phpfunction my_module_function() {
 
$my_data = &drupal_static(__FUNCTION__);
  if (!isset(
$my_data)) {
    if (
$cache = cache_get('my_module_data')) {
     
$my_data = $cache->data;
    }
    else {
     
// Do your expensive calculations here, and populate $my_data
      // with the correct stuff..
     
cache_set('my_module_data', $my_data, 'cache');
    }
  }
  return
$my_data;
}
?>
This version of the function still uses the static variable, but it adds another layer: database caching. Drupal's APIs provide three key functions you'll need to be familiar with: cache_get(), cache_set(), and cache_clear_all(). Let's look at how they're used.
After the initial check of the static variable, this function looks in Drupal's cache for data stored with a particular key. If it finds it, $my_data is set to $cache->data and we're done. Combined with the static variable, future calls during this page request won't even need to call cache_get()!
If no cached version is found, the function does the actual work of generating the data. Then it saves it TO the cache so future requests will find it. The key that you pass in as the first parameter can by anything you choose, though it's important to avoid colliding with any other modules' keys. Starting the key with the name of your module is always a good idea.
The end result? A slick little function that saves time whenever it can -- first checking for an in-memory copy of the data, then checking the cache, and finally calculating it from scratch if necessary. You'll see this pattern a lot if you dig into the guts of data-intensive Drupal modules.

Keeping up to date

What happens, though, if the data that you've cached becomes outdated and needs to be recalculated? By default, cached information stays around until some module explicitly calls the cache_clear_all() function, emptying out your record. If your data is updated sporadically, you might consider simply calling cache_clear_all('my_module_data', 'cache') each time you save the changes to it. If you're caching quite a few pieces of data (perhaps versions of a particular block for each role on the site), there's a third 'wildcard' parameter:
<?php
cache_clear_all
('my_module', 'cache', TRUE); ?>
This clears out all the cache values whose keys start with 'my_module'.
If you don't need your cached data to be perfectly up-to-the-second, but you want to keep it reasonably fresh, you can also pass in an expiration date to the cache_set() function. For example:
<?php
cache_set
('my_module_data', $my_data, 'cache', time() + 360); ?>
The final parameter is a unix timestamp value representing the 'expiration date' of the cache data. The easiest way to calculate it is to use the time() function, and add the data's desired lifetime in seconds. Expired entries will be automatically discarded as they pass that date.

Controlling where cached data is stored

You might have noticed that cache_set()'s third parameter is 'cache' -- the name of the table that stores the default cache data. If you're storing large amounts of data in the cache, you can set up your own dedicated cache table and pass its name into the function. That will help keep your cache lookups speedy no matter what other modules are sticking into their own tables. The Views module uses that technique to maintain full control over when its cache data is cleared.
The easiest place to set up a custom cache table is in your module's install file, in the hook_schema() function. It's where all of the custom tables used by your module are defined, and you can even make use of one of Drupal's internal helper functions to simplify the process.
<?phpfunction mymodule_schema() {
 
$schema['cache_mymodule'] = drupal_get_schema_unprocessed('system', 'cache');
  return
$schema;
}
?>
Using the drupal_get_schema_unprocessed() function, the code above retrieves the definition of the System module's standard Cache table, and creates a clone of it named 'cache_mymodule'. Prefixing the name of custom cache tables with the word 'cache' is common practice in Drupal, and helps keep the assorted cache tables organized.
If you're really hoping to squeeze the most out of your server, Drupal also supports the use of alternative caching systems. By changing a single line in your site's settings.php file, you can point it to different implementations of the standard cache_set(), cache_get(), and cache_clear_all() functions. The most popular integration is with the open source memcached project, but other approaches are possible (such as a file-based cache or against PHP's APC). As long as you've used the standard Drupal caching functions, your module's code won't have to be altered.

Advanced caching with renderable content

In Drupal 7, "renderable arrays" are used extensively when building the contents of each page for display. Modules can define page elements like blocks, tables, forms, and even nodes as structured arrays; when the time comes to render the page to HTML, Drupal automatically uses the drupal_render() function to process them, calling the theme layer and other helper functions automatically. Some complex page elements, though, can take quite a bit of time to render into HTML. By adding a special #cache property onto the renderable element, you can instruct the drupal_render() function to cache and reuse the rendered HTML each time the page element is built.
<?php
$content
['my_content'] = array(
 
'#cache' => array(
   
'cid' => 'my_module_data',
   
'bin' => 'cache',
   
'expire' => time() + 360,
  ),
 
// Other element properties go here...);?>
The #cache property contains a list of values that mirror the parameters you would pass to the cache_get() and cache_set() if you were calling them manually. For more information on how caching of renderable elements works, check out the detailed documentation for the drupal_render() function on api.drupal.org.

A few caveats

Like all good things, it's possible to overdo it with caching. Sometimes, it just doesn't make sense -- if you're looking up a single record from a table, saving the result to a database cache is silly. Using the Devel module is a good way to spot the functions where caching will pay off: it can log the queries that are used on your site and highlight the ones that are slow, or the ones that are repeated numerous times on each page.
Other times, the data you're using will just be a bad fit for the standard caching system. If you need to join cached data in SQL queries, for example, cache_set()'s practice of string data as a serialized string will be a problem. In those cases, you'll need to come up with a solution that's specific to your module. VotingAPI maintains one table full of individual votes and another table full of calculated results (averages, sums, etc.) for quick joining when sorting and filtering nodes.
Finally, it's important to remember that the cache is not long term storage! Since other modules can call cache_clear_all() and wipe it out, you should never put something into it if you can't recalculate it again using the original source data.

SOURCE: www.lullabot.com

Tuesday, April 14

Print table of given number.

//Program to print table of given number
    #include<stdio.h>
    #include<conio.h>
    int main()
    {
     int n,k=1,m;
     clrscr();
     printf("Enter the number\n");
     scanf("%d",&n);
     while(k<11)
     {
       m=n*k;
       printf("%d*%d=%d\n",n,k,m);
       k++;
     }
   
      getch();
      return 0;
    }


To Run this Program Copy it in text editor and save as .c
Then double click on it and then it will get opened in your compiler.
Click on run.

Print table of the numbers from 1 to 10

//Program to print table of the numbers from 1 to 10
    #include<stdio.h>
    #include<conio.h>
    int main()
    {
      int row, col;
      clrscr();
      printf("Table of 1 to 10 is as\n");
      for(row=1;row<=10;row++)
      {
        for(col=1;col<=10;col++)
        {
          printf("%4d",row*col);
        }
        printf("\n");
      }
      getch();
      return 0;
    }


To Run this Program Copy it in text editor and save as .c
Then double click on it and then it will get opened in your compiler.
Click on run.

Wednesday, April 8

Free space on your smartphone or tablet.



You're in the park with your family and one of the kids does something unbelievably cute. You quickly grab your smartphone to take a video and ... "Not enough room."

A full smartphone or tablet can't take pictures, download music, add new apps, or even install operating system updates that contain important security fixes. You need to free up some space fast, and I can tell you how without losing any important information.


Clear out apps

Apps can make your phone or tablet do some useful and amazing things. I have plenty of great apps from games and utilities to security and photo editors on my site, but they can fill up your available space before you realize it. You probably don't need every one of those latest-addicting-must-have game apps, or three to-do list apps.

In Apple, iOS 8, go to Settings >> General >> Usage>> Manage Storage. For iOS 7 and earlier, it's just Settings>>General>>Usage. Here you'll see a list of apps and how much space they use. This helps you make an informed decision about where to go fat-trimming. To delete an app you don't want, simply tap its name. Then tap the "Delete App" button on the next screen.

In Android, go to Settings >> Applications (Settings >> Application Manager on some gadgets). Swipe left until you end up on the "Downloaded" tab. Here you'll see a list of apps you've downloaded and how much space they use. To remove an app, just tap the name and then tap the "Uninstall" button. Start removing the apps you no longer use, then take a look at the largest apps that are left and think about how much you really need them.

With Android, you can also go to Settings >> Storage to get a detailed breakdown of how much space you have and what's using it, such as Apps, Pictures, Audio, Downloads, etc. Tapping a category will take you to the relevant area of Android. So, tapping on "Apps" will take you to the Application Management screen while tapping "Pictures" will take you to your photo gallery app.

In Windows Phone 8, go to the Start screen and swipe left to get the App list. Tap and hold an app and then tap "Uninstall." Tap "Yes," and the app will go away.


Organize your photos and videos


Smartphone cameras make it easy to snap dozens of pictures of that family outing, friendly get-together or just a funny random moment you see while out and about. Do that every couple of days for a year or two and it's no wonder your phone is full.

Take a look through your phone's camera app. Are there any accidental photos, such as photos of the floor, sky or doorway you can delete? Are most of your good photos already posted to social media?

To free up space, you can transfer and organize photos and videos on your home computer or online storage using programs like iPhoto, Dropbox or Picasa. With Android, you might also be able to plug your gadget into your computer and drag the files directly and then delete them from your gadget.

Your camera isn't just for photos; it can shoot video, too. A dozen one-minute videos you shot at birthday parties and other celebrations can take up gigabytes of space. You'll definitely want to move these over to a computer to free up space. You can also upload them to an online storage site like Dropbox or Google Drive, or put them on a video-sharing site like YouTube. If you don't want everyone seeing them, mark them as private so only people you choose can see them.


Stream music and movies

Your smartphone or tablet works great as a media player for music and videos, but those take up a lot of space. Instead of loading your entire media library on your gadget, consider using a cloud streaming service instead.

For iPhones and iPads, Apple's iTunes Match will hold your entire music library in the cloud and stream to you the songs you want. Sure it costs $25 a year, but that's much less than spending hundreds on a new gadget with more storage that will just fill up again.

Google Play Music is another solution. This service can hold your entire music library, including songs from iTunes, and stream your music to you whenever you want. The only space it takes up is for the Google Play Music app, not each individual song or album. There's also an option to get a subscription to add new music and movies, much like iTunes.

Of course that's not your only option for streaming music instead of storing it. Click here to explore more streaming music options that give you a nearly infinite music library.

When it comes to movies, just five feature-length HD movies will take up 15GB or more of space. That's all the space available on many gadgets and a large chunk of others.

If you purchased movies via iTunes, Amazon or Google Play, those are available in the cloud and you can stream them using each service's respective app. Don't forget you can also stream movies from Netflix, Hulu and other services using their apps.

Unless you're traveling and you won't have Wi-Fi access, you don't need to store movies on your gadget. If you are traveling, though, be sure to check out the VLC app (Android or iOS, Free) that can play any movie file. It cuts down on the headaches of making sure your movies are in the right format.

SOURCE: usatoday.com