Claudiu Persoiu

Blog-ul lui Claudiu Persoiu


Archive for the ‘php5.3’ tag

Closures, from Scheme to Javascript to PHP

without comments

The notion of closure in PHP, even though it appeared in PHP 5.3, as I’ve said before on my blog, it was properly done only in 5.4.

Wikipedia tells us:

In computer science, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables) of that function.

In PHP this isn’t a very popular concept or very well-known. It is often mistaken for Anonymous Functions. But in functional programming languages it is very popular, because they really need it!

Scheme

When Brendan Eich designed JavaScript, relied on the Scheme language and ended up doing an implementation of this language with a C syntax. The C syntax was and is a lot more popular, and back then (1995) the Java programming language was very “fashionable”.

The Scheme syntax is similar to Lisp, in the sens that is using parenthesis abound expressions in order to execute them. The operators are defined as functions and just like them, there must be placed left of the parenthesis.

Let’s take an Scheme closure example:

(define (make-counter)
  (let ((count (begin 
                 (display "run parent function and return 0") 
                 0)))
    (lambda ()
      (set! count (+ count 1))
      (begin 
        (display "inside child function ") 
        count))))

The function is setting a “count” variable, with the value 0 and displays “run parent function and return 0”, then returns another lambda function, that is incrementing the variable defined in the main function and then displays “inside child function”.

I’m storing the resulting function in a variable in order to later run it multiple times:

> (define counter (make-counter))
run parent function and return 0
> (counter)
inside child function 1
> (counter)
inside child function 2

In other words, each time I’m calling (make-counter), it will return a new function that has access to the environment at the time at which it was created. If it looks strange because of the syntax, I promise that it will fell a lot more natural in JavaScript.

This concept is very interesting for encapsulation. The environment from the time when the parent function was been executed can be encapsulated, and later it can be used without worrying that it was changed by external causes.

For the functional programming languages this is a very interesting concept. Yet when it comes to object orientated languages, the concept seems almost useless, because objects also have the purpose of encapsulation.

JavaScript

From the beginning JavaScript was a hybrid, a functional programming language, object orientated, with prototype based inheritance. And if this wasn’t enough, the syntax was taken from Java (C).

JavaScript didn’t inherited a lot from Scheme, but it did inherit the closure concept.

A reason why there was a need for closures in Scheme is that that if a function is not finding a variable in its environment, it will search for it in its container’s environment. Let’s take an example:

(define x 1)
(define (add-in-env y) (+ x y))

If we call add-in-env with 2:

(add-in-env 2) -> 3

It looks just as ambiguous as in JavaScript, but is not exactly like that. In Scheme to do mutation is not that easy, simple and transparent, so an subsequent operation of:

(define x 2)

will result in an error.

In JavaScript resulted a hybrid. Mutation is permitted, but the notion of searching a variable in the current environment remained:

var x = 1;
var add_in_env = function (y) {
   return x + y;
}

add_in_env(2); // returns 3

Up to this point is ok, but for:

x = 2;
add_in_env(2); // returns 4

For this case, things can get out of hand very easy:

But, in order to solve the issue, we can just define a variable in the environment that will finish execution (will close):

var make_counter = function () {
   console.log("run parent function and set counter to 0")
   var count = 0;

   return function () {
       count = count + 1;
       console.log("inside child function");
       return count;
   }
}

var counter = make_counter();
console.log(counter());
console.log(counter());

var counter2 = make_counter();
console.log(counter2());
console.log(counter());
console.log(counter2());

The output will be:

run parent function and set counter to 0
inside child function
1
inside child function
2
run parent function and set counter to 0
inside child function
1
inside child function
3
inside child function
2

Even though the main function finished executing, the environment inside it is kept as a closure for the function that was returned. Only when there aren’t any more references to the sub-function the memory allocated for the closure will also be deallocated.

Even though JavaScript has objects, it doesn’t have private methods. An approach is to add a “_” (underscore) in front of the function name and consider it private. From my point is like asking the developers that will later use the code to consider this function private. Of course this is not very consistent.

Let’s take an example:

var obj = {
   _secretFunction : function (key) { console.log(‘do secret ’ + key) },
   doStuff : function (key) { this._secretFunction(key) }
}

obj.doStuff(‘stuff’); // do secret stuff

It seems that there is a public method “doStuff” and a private one “_secretFunction”. Nevertheless you can not prevent a user from calling “_secretFunction” or even worse, to modify it:

obj._secretFunction = function (key) { console.log('new secret ' + key); }

obj.doStuff('stuff'); // new secret stuff

If we want to hide the function, and make this obvious for everybody, again, we can use closures:

var obj = (function () {
   var secretFunction =  function (key) { console.log(‘do secret ’ + key) }

   return {
      doStuff : function (key) { 
         secretFunction(key) 
      }
   }
})();

obj.doStuff(‘stuff’); // do secret stuff

Because the parent function was not stored but rather immediately executed, basically the space in which secretFunction was defined has already finished its execution, encapsulating the logic. The object returned can call the function because it was defined in the same environment as the object.

Looks complicated at first, but is really very easy when you understand the concept.

And then it was… PHP

PHP includes a lot of different options. It was originally developed as a Perl framework, later the engine was rewritten in C.

PHP is a dynamic language that includes a lot of concepts, from objects, interfaces and anonymous functions, up to goto labels. The development direction for the language is not very clear, it rather offers the possibility for different approaches.

In the weird PHP history, somewhere in version 4, syntax for Anonymous Functions was added, but only in PHP 5.3 a more “normal” version appeared.

Also in version 5.3 the first closure version was introduced:

$scalar = 5;

$closure = function () use ($scalar) {
     return 'Scalar: ' . $scalar . PHP_EOL;
};

echo $closure(); // Scalar: 5

$scalar = 7;

echo $closure(); // Scalar: 5

This version mostly worked, but you had to specify what you want to send to the closure.

And there were other inconveniences:

<?php 
class Foo {         
   private function privateMethod() {                 
      return 'Inside private method';         
   }

   public function bar() {                 
      $obj = $this;                 
      return function () use ($obj) {                         
         return $obj->privateMethod();
      };
   }
}

$obj = new Foo();
$closure = $obj->bar();
echo $closure();

Fatal error:  Call to private method Foo::privateMethod() from context '' in [...][...] on line 10

Is not working because you can not send $this as a parameter to a closure, and if you try the above trick you still can’t access the private methods. Remember, this was happening in PHP 5.3.

The idea to introduce a closure of this kind seems strange to me. But this is not the first time something “strange” is introduced in PHP, as I was saying before about the Anonymous Functions. Sometimes is looking like work in progress.

I think everybody was expecting a more JavaScript like closures. I think that JavaScript had a big influence in making this concept so popular.

In version PHP 5.4 things changed, we finally have a closure as we would expect:

class Foo {
   private function privateMethod() {
      return 'Inside private method';
   }

   public function bar() {
      return function () {
         return $this->privateMethod();
      };
   }
}

$obj = new Foo();
$closure = $obj->bar();
echo $closure(); // Inside private method

And it works!

You can even do:

unset($obj);
echo $closure();

and it will work, because the object in which the closure was defined remains in memory until either the script finishes execution, or a call like this is made:

unset($closure);

For more details on how closures work in PHP 5.4, check out this post.

Written by Claudiu Persoiu

10 April 2013 at 10:02 AM

There is life without PHP 6 – 2012 retrospective

with 3 comments

Another year has passed without native unicode support for PHP. Yes, PHP6 is not here yet, in case anybody was still asking…

But, the version that is now here is PHP 5.4. With this version only refinements were added, there weren’t changes as big as there were on PHP 5.3. In PHP 5.4, the big addition are “traits” and, my favorite, the new version for closure.

As the keywords for last year were Drupal and Magento, this year the keyword was only Magento.

A couple of months ago, more or less forced by the circumstances, I’ve taken the Magento Plus certification exam. For this certification, Optaros, my employer, had a major influence. We had been more or less made to take the exam and we also had to be part of a company level study group.

I haven’t been part of a study group since faculty, and I must admit that I’ve forgotten how useful it is. Colleagues with more Magento experience (unlike me who I’ve been working with Magento for a little more than an year), had helped a lot to clarify issues and to document them.

But more about this in another blog, that will follow shortly (I hope)…

Anyway, after studying Magento in so much detail, I must admit that I have a lot more respect for the platform. After you analyze the backend architecture, a different picture is emerging. The architecture is very interesting and quite flexible, which makes you overlook some of it’s shortcomings.

Now that a new year has begun, I wish I’m going to publish more, I think in the last period I haven’t been very “productive” when it comes to publishing, either text or code.

Also this year I want to take at least another certification exam. As the Magento certification was set only for this year, I still have a lot of options on my plate.

That’s about all for 2012 and plans for 2013.

I wish you an excellent 2013!

Written by Claudiu Persoiu

14 January 2013 at 9:54 AM

Posted in Diverse,PHP

Tagged with , ,

PHP 5.4 – Closures the right way!

with 5 comments

The concept of closure was introduced in PHP 5.3, with the new “more traditional” syntax for anonymous functions.

PHP 5.3

In PHP 5.3, a closure will rely on the term “use”, which was passing the variables to the anonymous function, making it a closure.

The problem is that the anonymous function will only be able to access the variables that have been passed with “use”. When it comes to objects, there are passed by reference by default, but scalar variables (int, string, etc.) are passed by value, as this is the default behavior in PHP 5+:

$scalar = 5;

$closure = function () use ($scalar) {
     return 'Scalar: ' . $scalar . PHP_EOL;
};

echo $closure(); // Scalar: 5

$scalar = 7;

echo $closure(); // Scalar: 5

Another problem is that you cannot pass $this when the anonymous function is declared inside an object, so only the public method and properties can be accessed inside the closure.

PHP 5.4

In PHP 5.4 the keyword “use” is optional, and the entire environment where the function was created is available inside the function.

The advantage is that when the anonymous function is created inside another function or method, the anonymous function has access to the environment where it was created, even after the execution of the environment is over. The objects from this environment will be unset, only after the last reference to the closure will be unset:

class testClass {

        private $changeableVar = 1;
        private $bigVar;

        public function __construct() {
                // Allocate a big variable so we can see the changes in memory
                $this->bigVar = str_repeat("BigWord", 5000);
        }

        /**
         * A method that returns the closure
         */
        public function closure() {

                return function () {
                        // Display the value of a private property of the object
                        echo 'Private property: ' . $this->changeableVar.PHP_EOL;

                        // Change the value of a private property of the object
                        $this->changeableVar = 2;
                };
        }

        /**
         * Method that displays a private property
         */
        public function showChangeableVar() {
                echo 'Private property in method: ' . $this->changeableVar.PHP_EOL;
        }

}

// Memory befor the objects is created
echo "Memory: " . memory_get_usage() . PHP_EOL; // Memory: 229896

// Create object
$testObj = new testClass();

// Create closure
$closure = $testObj->closure();

// Execute closure
$closure(); // Private property: 1

// Displaying the current value of the private property
$testObj->showChangeableVar(); // Private property in method: 2

// Memory befor object will be unset
echo "Memory: ". memory_get_usage() . PHP_EOL; // Memory: 266240

// Unset the object
unset($testObj);

// Memory after the object was distroyed, there is no big difference in memory
echo "Memory: ". memory_get_usage() . PHP_EOL; // Memory: 266152

// Run closure after the object in which it was created was unset
echo $closure(); // Private property: 2

// Unset closure and with it the object environment
unset($closure);

// Memotry after the las reference to the object (closure) is unset
echo "Memory: " . memory_get_usage() . PHP_EOL; // Memory: 230416

Callable type hinting

Another new feature introduced in PHP 5.4 regarding closures is the new “type hint”: “callable”. Actually callable is referring to any anonymous function, and even to a new way of calling a method of an object:

<?php

// A function that uses type hinting
function typeHinting(callable $a) {
     echo $a() . PHP_EOL;
}

// A closure
$closure = function () {
     return __FUNCTION__;
};

// Call the type hinting function with the closure
typeHinting($closure); // {closure}

class testClass {
     public function testMethod() {
          return __METHOD__;
     }
}

// A mock object
$testObj = new testClass();

// The new way of calling object methods
$objCallable = array($testObj, 'testMethod');

// Call type hinting function with the new method calling way
typeHinting($objCallable); // testClass::testMethod

I believe that only now we can really say that PHP supports closures, the right way!

Written by Claudiu Persoiu

11 February 2012 at 5:10 PM

Posted in PHP

Tagged with , , , ,

Another year has passed an PHP 6 remains a myth – 2011 in review

without comments

It became a tradition for me to begin my annual review on this subject.

PHP 6 is as close to be released as it was last year, or two years ago, which is without perspective. This year PHP 5.4 reached RC4 and a final version will probably be released soon, this means that work on PHP 6 will not be resumed soon. But more about PHP 5.4 with another occasion, is on my “TODO” list to see what got into RC4.

As the main keyword for me in PHP 5.3 were namespaces, Anonymous functions, closures and garbage collector, in PHP 5.4 it seems that those keywords are going to be traits, the new closures and scalar type hinting, next to many other new features.

When I’ve wrote my first annual review blog about PHP 6, I was mainly working on Romanian websites, hence my desire for a version that will natively support this language and any other without any changes. Back then I was mainly working directly with the language, without using a framework most of the time. But since then a lot of time has passed and many things have changed, now I’m using almost exclusively frameworks and other platforms that are taking me further away from the language, offering me a different architectural perspective.

After more then an year with NCH, I’ve decided that is time for a change. This is also a company from the states with a branch in Romania, and this time is Optaros. Although I wasn’t trying to change my work place, I’ve responded to an invitation to an interview, and long story short, I left. For a long time I’ve wanted to work again for external clients, after working at NCH where all the projects were internal, I’ve wanted a change.

Again the projects are even bigger, with other scalability issues. But I think that makes web development so interesting, the bigger the scalability issues, the bigger the project.

Last year the main keywords were Linux si Symfony framework. For this year that is just ending the main keywords probably were: Magento and Drupal.

After a short period of working with Magento, I can say that it seems incredible how a platform so big has so little documentation and a lot of the time so inconsistent. It is a very complex platform and a lot of things can be done with it, but when it comes to documentation, it seems like the usual approach is to just analyze the core. Coming from the Symfony world, where there are literary books for documentation, available for free, it seems incredible how little and disorganized is the Magento documentation. But this is also a subject for another blog. A think that the Optaros team played an important role in helping me understand how to approach the issues.

Another major event for me this year was the Yahoo! Open Hack Day, event that this year was also held in Romania. I don’t think I’ve ever seen so much enthusiasm and energy in a single place, in a single day. For me as a developer it was an unforgettable experience, one of those moments that remind me why I’ve chosen this profession.

Also this year I’ve passed my PHP 5.3 certification exam, at the beginning of the year. The exam wasn’t as difficult as I’ve expected, even though the tension remains the same. The fact that it wasn’t my first certification exam helped, it’s incredible how much you remember when you start the reading the documentation again. Last year I’ve decided that I have to take at least an certification exam every year, so I have to get started on preparing for the next one.

As a conclusion, 2011 was a good year, full of challenges and accomplishments, even though I haven’t checked a lot of entries on my last year’s resolution, I’ve done quite a few that were not on that list. But now is time for another new year’s resolution.

And now I wish you an 2012 full of achievements! Happy new year!

Written by Claudiu Persoiu

3 January 2012 at 4:45 PM

Posted in Diverse

Tagged with , , , ,

PHP 5.4 Alpha 1 is here!

without comments

Three days ago, that is on 28-06-2011 the PHP 5.4 alfa 1 version was announced on ww.php.net!

Basically in this release are the things that were made for PHP 6 and did not make it in PHP 5.3, next to some other new features.

Some of the most interesting new features are:

Traits

A new OOP feature. Basically for horizontal code reuse, that is inheriting of methods instead of extending classes.

trait Inharitable {
    public function test() {
        echo 'Class: ' . __CLASS__ . ' Method: ' . __METHOD__ . PHP_EOL;
    }
}

class A {
    use Inharitable;
}

class B {
    use Inharitable;
}

$a = new A();
$a->test(); //Class: Inharitable Method: Inharitable::test

$b = new B();
$b->test(); //Class: Inharitable Method: Inharitable::test

Traits in PHP 5.4 are the new namespaces of PHP 5.3, that is the most interesting feature in PHP 5.4.

Scalar type hinting

Up to PHP 5.3 there was type hinting only for classes, interfaces and arrays. With PHP 5.4 type hinting can be used for scalar data types like: int, string, float, book and resource.

function test(string $var) {
  echo $var;
}

$a = 'aa';
test($a);

Unfortunately on this alpha version on my computer I get: Catchable fatal error: Argument 1 passed to test() must be an instance of string, string given, called in .. on line 58 and defined in … on line 52

What can I say… it is still an alpha…

Closures

Yes, I know, there are closures in PHP 5.3 too, but there are not the same. In PHP 5.3 if you wanted a closure you had to use the keyword use and then specify the variables that the lambda functions will have access to.

In PHP 5.4 it’s beginning to look more like JavaScript, in a good way:

class closureTest {

    private $a;

    function test() {
        $this->a = 'object var';
        return function () {
            echo $this->a;
        };
    }
}

$a = new closureTest();
$b = $a->test();
$b(); // object var
unset($a);
$b(); // object var

Closure in the right way, with a lambda function the way it should be! Just like lambda functions existed even before PHP 5.3, but only after the new syntax they’ve become popular, now there was closures time.

This are some of the things that I find most interesting, but there are only a part of the new features that PHP 5.4 brings!

It’s likely that before the end of this year the final version will be ready.

I’m curious if with the final version of PHP 5.4 a new certification will come out, taking in consideration that the changes are not major.

Written by Claudiu Persoiu

1 July 2011 at 8:27 AM

Closures and lambda functions in PHP vs. JavaScript

with 2 comments

JavaScript and PHP support both lambda functions and closures. But the terms are poorly understood in both programming languages ​​and are often confused with each other.

Lambda functions

Also called anonymous functions. They refer to functions that can be called without being bound to an identifier. One of their purposes is to be passed as arguments. The Lambda name was introduced by Alonzo Church, inventor of lambda calculus in 1936. In lambda calculus all functions are anonymous.

JavaScript

In JavaScript lambdas are part of the standard set and there are the preferred method of defining functions.

For instance:

var add = function (a, b) {
     return a + b;
}
alert(add(1, 2)); // 3

Lambda functions are used almost in any context when it comes to JavaScript, like:

window.onload = function (e) {
     alert('The page has loaded!');
}

PHP

In PHP, lambda functions were introduced in version 4.0.1 using create_function. In version 5.3+ a similar syntax to JavaScript was added, a much more readable and elegant way of defining a function.

This means that in PHP there are two ways of creating a lambda function:

// PHP 4.0.1+
$add = create_function('$a, $b', 'return $a + $b;');

// vs.

// PHP 5.3+
$add = function ($a, $b) {
     return $a + $b;
};

echo $a(1,2); // 3

Lambda functions can be used as parameter for other functions, such as usort:

$array = array(4, 3, 5, 1, 2);
usort($array, function ($a, $b) {
     if ($a == $b) {
          return 0;
     }
     return ($a < $b) ? -1 : 1;
});

Even more, PHP 5.3+ allows calling an object as a anonymous function:

class test {
     function __invoke($a) {
          echo $a;
     }
}
$a = new test();
$a('test'); // 'test'

Closures

The closure is really the misunderstood concept of the two. In general confusion appears because closures may involve lambda functions. A closure refers to the ability of a function/object to access the scope in which it was created even if the parent function has ended it’s execution and returned. In other words, the function/object returned by a closure is running in the scope in which it was defined.

In JavaScript the notion of closure is part of the standard arsenal, because the language is not based on the traditional object model, but rather on prototypes and functions. But JavaScript has some traditional object model parts, like the fact that you can use “new” to construct an object based on a function that plays the role of a class. In PHP closures are more of an new way to approach problems, because PHP is part of the traditional object model family.

JavaScript

In JavaScript the notion of closure is widely used, it’s so popular because JavaScript is not a traditional object orientated language, but rather a functional one, based on prototype inheritance.

JavaScript doesn’t have Public, Private and Protected, but rather only Public and Private and objects an inherit from each other, without using classes.

Another issue is the scope, because the global scope is used by default. This issues can be fixed in an elegant fashion using closures:

var closure = function () {
     var sum = 0;
     return {
          add: function (nr) {
               sum += nr;
          },
          getSum: function () {
               return sum;
          }
     }
}();

closure.add(1);
closure.add(2);
console.log(closure.getSum());

In the example above, sum is a private property and in theory can only be accessed and modified by the closure function. The interesting part is that the parentheses from the end of the function definition, signify that this function will be immediately  executed and therefore will return the result which is an object. At this point the original function will only exist for serving the return object, encapsulating therefor the private variable.

Although the function has finished execution, through this closure the returned object can still access the variables defined in the function scope, because that was the environment in which it was created.

This becomes even more interesting when a function returns another function:

var counter = function () {
    var counter = 0;
    console.log('in closure');
    return function () {
        console.log('in the anonymous function');
        return ++counter;
    };
};
var counter1 = counter();

console.log(counter1()); // 1

var counter2 = counter();
console.log(counter2()); // 1
console.log(counter1()); // 2

The output will be:

in closure
in the anonymous function
1
in closure
in the anonymous function
1
in the anonymous function
2

What actually happens is that the first function is executed and returns an anonymous function that can still access the environment in which it was created. In my opinion this is where the confusion between closures and lambda functions comes from, because a function returns another function.

The difference between examples is that in the first one the closure function executes immediately, and in the second example when counter is executed it’s returning a result that is actually a function definition, which in turn can be executed. Of course the second example can be modified to act just like in the first example using parenthesis.

PHP

As I said above, the notion of closure in PHP is not as important as in JavaScript.

Considering that lambda functions are available in the language since version 4, closures only appeared with PHP 5.3+.

Because of the block scope nature of PHP, there is a better encapsulation but there is a lot less flexibility compared to JavaScript. Basically in PHP you must specify using the use instruction what will the anonymous function be able to access from the closure scope.

function closure () {
     $c = 0;
     return function ($a) use (&$c) {
          $c += $a;
          echo $a . ', ' . $c . PHP_EOL;
     };
}

$closure = closure();

$closure(1);
$closure(2);

Unlike JavaScript, in PHP closures can not return objects, or rather the object can not be bound to the scope in which it was created, unless you send the variables as a reference to the constructor, in which case is not very elegant and I can’t imagine a scenario that would absolutely need closure for this.

Like in the JavaScript examples, instead of parentheses “()” at the end of the function, in PHP to run a function immediately after defining it call_user_func() or call_user_func_array() can be used:

$closure = call_user_func(function () {
    $c = 0;
    return function ($a) use (&$c) {
        $c += $a;
        echo $a . ', ' . $c . PHP_EOL;

    };
});

$closure(1);
$closure(2);

Written by Claudiu Persoiu

16 April 2011 at 6:02 PM

Passing Zend PHP5.3 Certified Engineer Exam

with 3 comments

As I was saying in a previous blog, when Zend launched the new ZCE 5.3 certification I’ve received an discount voucher code, available until the end of year 2010. I wanted to use this opportunity, so in the last week of the year I’ve bought the voucher.

I already had the experience of the ZCE 5 certification, about which I’ve blogged at that time.

I wanted to take the exam before the end of the vacation, that is 7-I.

The period was a little short, in theory, I had about two weeks to prepare, but because they ware around the hollydays the time was in fact way shorter.

Zend PHP5 Certification Study Guide – 2nd Edition

I’ve begin my study with Zend PHP5 Certification Study Guide – 2nd Edition. The book even though it does not have the latest 5.3 features is not outdated. Because it wasn’t the first time I was reading it, it felt more like a recap. I’ve tried for each chapter to create an example that will show the functionality and one that shows the cases where the functionality was not as expected. With all this in 4 days I was able to go through the entire book.

As a suggestion, for streams and SPL for instance where is a little difficult to study directly form the manual, the guide looks like a good start.

Because after all the book is a guide, as I was reading the book, I’ve looked in the corresponding chapters in the php.net manual for a more detailed view on the subjects.

Mock tests

Before I finished reading the first book I’ve took a PHP5 mock test and to my surprise the result was “Excellent”. I got the mock tests from when I took the ZCE 5 exam, and because a lot of the questions are repeat quite frequently, I’ve only used 3 back then. This time I’ve only took a couple of them for the same reason. The tests are quite useful for the PHP5 part because, just like there ware described, they are usual more complicated then the exam itself. But don’t take to many of them, especially if the first results are poor, because they may lead you in a false self trust because of the repetitive questions.

Zend PHP 5.3 Study Guide

When I’ve finished reading the first book I started reading the free Zend PHP 5.3 Study Guide, which can be downloaded from the certification page, in the right. The guide is in beta version and you can really feel that. Everyone who’s been talking (blogging) about it is saying that it is full of bugs, and after all that is true. One of the funniest bugs in my opinion is at page 109, question 12, the answer is D… which is not displayed in the page. But I believe that where there are bugs they will be easily discovered and will not mislead.

It feels a lot more like a guide then the previous book, is a lot more concise and abstract and if forces you to study the manual.

At the end of each chapter there are questions, I only had 100% on a couple of chapters. The questions a quite difficult, even more difficult then the questions in the actual exam in my opinion. You have to read each question carefully because in the exam there are the same type of questions.

To go through the entire guide it took me another couple of days because I was already warmed up from the precedent book.

The day before the exam

I’ve read on Lorna “lornajane” Mitchell‘s blog that before the exam is good to recap some delicate subjects. In the day before the test I’ve started to recap some subjects that need more memory then intellect, like the tens of functions for string si array manipulation. Also I think is a good idea to recap SPL.

The exam it self

After not a lot of studding the moment of the exam was here.

Just like the last time, I’ve schedule my exam over the Internet a day before and just went to the Pearson VUE center.

The exam itself didn’t feel more difficult then the PHP 5 one. In my opinion there is more focus on high level OOP and SPL then the previous exam. The style of the questions is quite similar, maybe a little more “type in” questions, but that can be just my luck because the questions are dynamically selected from a question pool with different difficulty levels.

The 90 minutes time has quite enough to go through all the questions whit all the attention required and to review the answers I wasn’t sure about. At the ZCE5 exam I’ve finished about a half of hour before the time. This time for ZCE 5.3 I’ve finished only 10 minutes early because I’ve tried not to rush at all.

READ CAREFULLY! Is very important to read each question carefully and read in again until you are sure you understand what is required of you. Some questions have a quite awkward formulation and can mislead very easy. Don’t panic, if you have doubts maybe you should mark the question for review and come back to it in the end.

I usually mark the first question of the exam for review because I’m nervous and I can’t focus enough.

Unlike 2 years ago, when I was working a lot more with raw PHP and even had some PHP 4 servers, last year I’ve worked most of the time with open-source frameworks. This can be a disadvantage because I’ve didn’t use just as much the core functions. But unlike the first certification I must admit I didn’t study as much, probably is because of experience and the fact that occasionally I flick through the pages of the guide.

And with that being said it is time to put the first check on the year resolution and add a new logo to my blog.

For those who are preparing, I wish you the best of luck!

Written by Claudiu Persoiu

8 January 2011 at 1:56 PM

Another year has passed and PHP 6 will not arrive

with 4 comments

Another year has passed and PHP 6 will not arrive.

Actually for the last couple of years I’ve been expecting PHP 6, and I believe this is more of a traditional blog for me to close the year.

PHP 6 will not come because the trunk was abandoned and rebuild from a 5.3.

Even if PHP 6 will not be out for a while now, PHP 5.3 is gaining popularity. Frameworks like Zend Framework and Symfony are each preparing in 2011 a 2.0 version that will need PHP 5.3+ to run. Even CodeIgniter, a framework that is was traditional PHP 4 compatible will need at least PHP 5.1.6 for version 2.0.

Even more, the official Zend certification for PHP is now ZCE 5.3, and it’s becoming very popular, even if it was released just few months back.

But a new year is ending and is time to check achievement from last year’s resolution and to write a new one.

Last year I’ve finished my masters, and with it I’ve finished way to many years to want to count of school. In fact this is the firs winter that I’m not in some form of school, maybe this is why I feel like I have so much free time :).

I’ve change my work place, and with it I was forced to use some things that were on my TODO list for quite some time:

  • Linux
  • Symfony Framework
  • Linux was a subject around I was gravitating inevitable for years, but never got to in to deep. It was always on my “todo” list, but never got the time or patience to really get into much detail with it, or didn’t have the continuity when I did it. When I got to my new work place I found my self in front of a Ubuntu computer, and I’ve started to panic a little.

    After few months I’ve made a new step, and for the first time in my life I went to a professional course. The course was organised by Info Academy. Paid from my own pocket and a little overlapped with my work hours. But I’ve reached the conclusion that I had to do it. Probably it does not sound like a big deal, but I usually study on my own, and it was quite weird for me. Now that is over I can say that it was a great investment and I recommend it (to all from Romania that can go to this centre).

    Sometime during that course I’ve realised that it was time to boot in linux from time to time even at home. The next step was to reconfigure the boot manager to boot directly to linux. Now that I’m almost exclusively use linux, I’ve reached the conclusion that is user friendly enough to be a real alternative to Windows.

    Symfony framework is another dusty entry on my “todo” list. Even if I’ve been playing around before with CodeIgniter and Zend Framework, I’ve never even got near to Symfony until last year. I’ve felt the fundamental difference of concept between ZF and Symfony. This was another reason to panic at my new work place, and after all: “all frameworks suck”.

    Is not a very easy to learn framework because of the concepts, but I thing it worth it. What I like most about this framework is the CRUD generating, that is very easy to do but is very powerful and flexible. Another thing is the use of YML files, which was taken from Ruby on Rails, is a way better alternative to the PHP’s native ini files.

    In the end, 2010 was a good year, with lot’s of achievements, even if I didn’t check everything on my last year’s resolution, I think I’ve checked enough.

    And now I wish you a great and full of achievements 2011! Happy new year!

    Written by Claudiu Persoiu

    31 December 2010 at 5:38 PM

    Posted in Diverse,PHP

    Tagged with , , , , ,

    The new ZCE PHP 5.3 certification

    without comments

    Since PHP 5.3 was released last year I’ve been wandering if Zend was going to introduce a new ZCE certification for this version.

    Seems like with the version PHP 6 abandoned some time back the direction was to a PHP 5.3 certification.

    I don’t think the time was random considering that Zend Con, the biggest PHP conference, is near.

    What’s new?

    Differences between PHP 5 and PHP 5.3 are in the manual here.

    Some of the most important once:

    Materials

    The certification information is on the Zend website.

    After finding that the certification for Zend Framework has a study guide completely free for registered users, I was wandering why there isn’t one for the regular PHP certification. It looks like now there is: Zend-PHP-5.3-Study-Guide-v1-3.pdf, in beta version! And is free for download!

    Of course the most important material remains the manual manualul PHP, because the guide is used in conjunction with it.

    It looks like the mock tests are out, as for the Zend Framework never existed anyway.

    Price

    The price has gone up, it isn’t 160$ anymore but 190$! The price remains a very small one anyway considering that an exam at Sun was 200$, and now at Oracle is 300$.

    The already certified users receive an 20% discount until the end of the year, so if you are already certified you will pay 152$.

    Best of luck!

    Written by Claudiu Persoiu

    17 October 2010 at 12:12 PM

    Posted in PHP

    Tagged with , , ,

    Factory method pattern using PHP 5.3 and late static bindings

    without comments

    Factory method design pattern introduced by GoF (Gang of Four) which I’ve talked about in a previous blog, has the base idea of a method that generates objects. Most implementations are “poor”, because they use a lot of hard-coding for the factory (just like me in the previous blog).

    PHP 5.3 offers the possibility of a very interesting implementation using “Late static bindings“.

    The classes from which the objects will be generated are:

    // abstract base class that will be inherited
    abstract class Drink {
    
        // ingredients
        protected $ingredients;
    
        // public method for producing the drink
        abstract public function MakeDrink();
    }
    
    // a child class for tea
    class Tea_Drink extends Drink {
    
        // ingredients for tea
        protected $ingredients = array('tea', 'sugar', 'mink', 'water');
    
        // make tea
        public function MakeDrink() {
    
            // make tea
        }
    }
    
    // another class for Bloody Mary
    class BloodyMary_Drink extends Drink {
    
        // ingredients for Bloody Mary
        protected $ingredients = array('votka', 'salt', 'tomato juice');
    
        // make Bloody Mary
        public function MakeDrink() {
    
            // make BloodyMary
    
        }
    }

    The idea is to have an abstract factory class to extend as simple as possible when creating each new factory class.

    PHP 5

    In PHP 5 the class will look something like this:

    // abstract Factory class
    abstract class absFactory {
    
        // name of the base class
        static protected $base_class = '';
    
        // factory method
        public static function getInstance($type) {
    
            // name of the resulting class
            $class_name = $type . '_' . self::$base_class;
    
            // check if class exists
            // here you can add an autoloader
            if(!class_exists($class_name)) {
                throw new Exception( 'Class ' . $class_name . ' not loaded!');
            }
    
            // check to see if the class inherits the base class
            if(!is_subclass_of($class_name, self::$base_class)) {
                throw new Exception(
                    'Class ' . $class_name . ' is not a child of ' . self::$base_class
                );
            }
    
            // new object
            return new $class_name;
    
        }
    
    }

    Because the getInstance() method is static the property will be static too.

    If we try:

    class DrinkFactory extends absFactory {
    
        static protected $base_class = 'Drink';
    }
    
    try {
    
        $obj = DrinkFactory::getInstance('Tea');
    
    } catch (Exception $e) {
    
        echo $e->getMessage();
    }

    The output will be:

    Class Tea_ not loaded!

    Because of the “self”, we can’t just call the method using the child class because the value of $base_class will be “” and not “Drink”, we must overwrite the getInstance() method. Which is quite “complicated”.

    A working version in PHP 5 will be:

    class DrinkFactory extends absFactory {
    
        public static function getInstance($type) {
    
            self::$base_class = 'Drink';
    
            // factory method of the base factory class
            parent::getInstance($type);
    
        }
    
    }
    
    try {
    
        $obj = DrinkFactory::getInstance('Tea');
    
    } catch (Exception $e) {
    
        echo $e->getMessage();
    }

    But is not exactly “elegant”.

    PHP 5.3

    Here we have “Late static bindings”, which is basically introducing the work “static”.

    The base factory class will look something like this:

    // abstract Factory class
    abstract class absFactory {
    
        // name of the base class
        static protected $base_class = '';
    
        // factory method
        public static function getInstance($type) {
    
            // name of the resulting class
            $class_name = $type . '_' . static::$base_class;
    
            // check if class exists
            // here you can add an autoloader
            if(!class_exists($class_name)) {
                throw new Exception( 'Class ' . $class_name . ' not loaded!');
            }
    
            // check to see if the class inherits the base class
            if(!is_subclass_of($class_name, static::$base_class)) {
                throw new Exception(
                    'Class ' . $class_name . ' is not a child of ' . static::$base_class
                );
            }
    
            // new object
            return new $class_name;
    
        }
    
    }

    The differences from the PHP 5 are marked with bold. A change so small allows us to create a much “nicer” factory class:

    class DrinkFactory extends absFactory {
    
         static protected $base_class = 'Drink';
    
    }
    
    try {
    
        $obj = DrinkFactory::getInstance('Tea');
    
    } catch (Exception $e) {
    
        echo $e->getMessage();
    }

    Basically in this version only the relevant property in this context is overwritten.

    Written by Claudiu Persoiu

    24 January 2010 at 5:46 PM

    Posted in Design patterns,PHP

    Tagged with , , ,