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);

?>