Claudiu Persoiu

Blog-ul lui Claudiu Persoiu


PHP 5.6 awesomeness!

with 2 comments

The year has just started and a new PHP version is preparing for release. At the time when I’m writing this blog, it is in alpha 2. It can be downloaded from here: snaps.php.net.

There is a series of interesting features, but today I’ll approach only 3 of them: constant scalar expressions, variadic functions and arguments unpacking.

Constant scalar expressions

This first feature is also the only one that didn’t have an equivalent before this version. And, when I say equivalent, I mean only for classes.

Until now, constants defined using the keyword “const” didn’t allow any type of expression, only a scalar value could be used, ex:

const INT_CONST = 1;

const STRING_CONST = "string";

const HEREDOC_CONST = <<<'EOT'
nowdoc
EOT;

Of course, there is also the more interesting version, which allows setting constants with dynamic values:

define('DYN_CONST', $variable);

The bad part is that this type of constants are not available for a class, because for a class only const can be used.

This means that now we can use:

const ONE = 1;
const TWO = ONE * 2;
const STR = "string of one and two :" . ONE . TWO;

And if it’s not enough, there is always:

define('FLAG', true);

const EXP = FLAG ? ONE : TWO;

Basically, we can set dynamically a value for a class constant! For instance, you can set like this in a constant the environment type for the user, dev or prod.

Variadic functions

This is the feature that I like the most, even though there is an equivalent for it in the older versions.

Currently, if you want to create a function with a variable number of parameters, you can:

function variableParameters () {
     $params = func_get_args();
     foreach ($params as $parameter) {
          echo $parameter . PHP_EOL;
     }
}

variableParameters(1);
variableParameters(1, 2);
variableParameters(1, 2, 3);

There are several problems, more or less obvious, with an approach like this:
1. From the function signature it is not clear that it accepts more parameters, on the contrary, it seems that it doesn’t take any;
2. func_get_args can be called anywhere in the function. If it’s on the first line, the purpose will be obvious, if it’s on line 20, it’s hard to spot and may generate confusion.

An alternative is to add a number of parameters, but this is not a good indication of the varying behavior.

And here is the new approach:

function variableParameters (...$params) {
     foreach ($params as $parameter) {
          echo $parameter . PHP_EOL;
     }
}

In this new version, it’s clear what is happening with the function parameters. You don’t have to figure out if and how many parameters the function can take, it is clear that the number varies!

Usually, when I’m looking for a function, I look for the definition in the IDE before checking out the documentation, especially when there is little or no documentation.

Arguments unpacking

The problem that is approached here is: there is a function with multiple parameters and they are sent in a dynamic fashion.

As I was saying previously, there are alternative ways to solve this problem. Let’s use the function from the previous example:

function variableParameters () {
     $params = func_get_args();
     foreach ($params as $parameter) {
          echo $parameter . PHP_EOL;
     }
}

And let’s say there is a variable number of parameters, moreover they are stored in an array. We don’t have a lot of options to pass them:

$params = ['param1', 'param2', 'param3'];

call_user_func_array("variableParameters", $params);

The result will be:

param1
param2
param3

In PHP 5.6 we can use those 3 points, similarly to the way they were used in the example from “Variadic functions”, but the other way around. Instead of the parameters that are received by the functions, they are the parameters being sent to it:

variadicParameters(...$params);

Maybe for this type of example it is not very clear, but if there is a fixed number of parameters for the function and a fixed number of parameters that are sent:

function twoParams($a, $b) {
     echo $a . $b . PHP_EOL;
}
$params = ["Hello", "PHP 5.6!"];

twoParams(...$params);

Even though it’s not something that couldn’t be done in the previous versions, now it’s more elegant.

And to conclude, the two examples:

function variableParameters (...$params) {
     foreach ($params as $parameter) {
          echo $parameter . PHP_EOL;
     }
}

variableParamerers(...["cool", "parameter", "unpacking"]);

I think with these small changes, PHP is making the transition from “the PHP way” to “the best way”, taking from other languages.

Written by Claudiu Persoiu

22 February 2014 at 10:17 PM

Posted in PHP

Tagged with ,

Nope PHP 6 is not here… but how about 2013?

without comments

This is a retrospective of the year that has just ended.

In case anybody is still wandering, no, PHP 6 didn’t come out and it will probably not come out any time soon.

Why is it relevant? Since I started this blog, at the end of each year I had a post related to PHP 6 and the fact that it wasn’t released. In 2008 it was a popular question, but nobody is wondering  about that anymore, and so I will close this subject now. Let’s return to the year that has just ended.

Close to the middle of the year, the version PHP 5.5 was released, bringing features like: finally , generators and many other enhancements.

Like in 5.4, these are not defining features for the language. In this new version, there are functionalities that can be easily replaced, but if present, they are welcome.

Even though PHP is proving very dynamic lately, I think this year the main keywords were HTML5 and JavaScript.

HTML5 is seeing a lot of improvements and older components begin to have more momentum. The companies are beginning to invest in games that work in the browser using WebGL. Even older games are getting ported to the platform, using technologies like asm.js.

And, because I’ve brought games into the subject, it seems very interesting to me how only 5-7 years ago the games built with JavaScript were relatively simplistic, and now they can be compared with the ones from PCs and consoles.

I think the web revolution, which many were expecting, is taking shape. Finally the Web is a platform in the true meaning and JavaScript a language truly appreciated.

The success is due to all sides, it is not only about ECMA or only about browser manufactures, now it is truly dynamic. The Web revolution is in full blow!

When it comes to backend, the spotlight was on Node.js. It is becoming an important player on the market. New frameworks have appeared  and it isn’t a platform mainly used by hackers eager to explore new technologies anymore, but also by large companies, like PayPal, LinkedIn and Yahoo, adding a vote of confidence to it. I think Node.js is finding its place and a niche in the market, and, as a JavaScript fan, I can only be happy.

An advantage of Node.js is that you don’t have to take into consideration different JavaScript versions, like in the browser. It allows the use of the latest features from ECMA freely, an environment where you can develop JavaScript with not headaches.

Technically speaking, it was a very interesting year for web development.

Finally, I want to wish you all an extraordinary 2014!

Written by Claudiu Persoiu

19 January 2014 at 11:10 PM

Posted in Diverse

Tagged with , , ,

The epic code from the movies

without comments

In movies where hackers appear, source code appears flowing in rivers on the screen. Looks important, seems like there is a computer genius that is preparing to revolutionaries something.

Ever wandered what that epic code from the movie is? John Graham-Cumming has done a collection of movies and the source code used in them: http://moviecode.tumblr.com/.

Written by Claudiu Persoiu

5 January 2014 at 12:07 PM

Posted in Diverse

Appcelerator Titanium – few impressions

without comments

Note: Titanium and PhoneGap are a couple of platforms for developing hybrid applications for mobile. These platforms are not written in the programming language that is native to the phone, but they can be distributed on a verity of mobile platforms.

Recently I’ve published on Github the newest and most extraordinary quizzing platform, named Just-Quizzing. I’ve build it for personal use, but because a few colleagues found it useful, I made it public.

In the initial version, for publishing the application to my Android phone, I used SL4A. I needed a way to use the application when I was on the move and didn’t have Internet access. Unfortunately it didn’t have automatic update for the quizzes. I’ve hoped that with time SL4A will have a clearer path, but the platform lost its initial momentum and I decided to write a mobile app.

I had to choose between PhoneGap and Titanium. In the past I’ve used PhoneGap because the app size was too big in Titanium, but I wanted to give it another go. In 2011, when I first wrote about Titanium, the initial app size was about 4M. Today it doesn’t seem that big, even though it isn’t small.

The perspective will be mostly about Android, even though the app was built to work also on iPhone.

I used SDK 3.1.3, without the Alloy framework.

Alloy has it’s own learning curb and I wanted to avoid it. The prupose of the application was to be a portable version for the quizzes from the server and I didn’t want to make a big time investment.

The total development time was a little more than a week.

First impression

Things don’t work as you expect them to, there isn’t a lot of flexibility. From the total allocated time, more then a quarter I was trying to do a “flyout menu”, like in applications such as: Facebook, Google Plus and Youtube. It was a total disaster! The only options that seemed to work were using an external module or using Alloy widgets.

It seems like when converting relative coordinates, where the user touched the current element, to the general coordinates on the screen there is a big discrepancy and it is impossible to do a sliding menu effect in a decent manner. In the end I totally abandoned this effect.

The speed is not that good when it comes to rendering elements. To be honest, I was expecting a better speed. There are some tricks that help, like pre-rendering the views before displaying them, but for this you must guess what the user will do next, which is not always possible.

Another thing that bothered me was that when the menu button is pressed on Android you can’t take a particular action, let’s say open the side menu that I’ve mentioned before. In PhoneGap for instance, no menu is opened, it must be built-using HTML from the ground up.

When Titanium came out, they were stating that you could develop once and distribute to multiple platforms. Now I was surprised to find that the approach had changed. In the Kitchen Sink, the application that showcases the features of the platform, each platform type initializes the application in it’s own file. One of the reasons is that the design is done dynamically if you are not using Alloy, not trough layout files.

One of the first things that I tried with Titanium was to see the size of a “Hello World” app. Packed, the application has about 8.5M, installed on the phone, it takes up about 16M. I don’t know what you think about that, but for me it is a lot! What is strange is that my final app occupies about 8.4M packed and installed about 16M, almost identical to the original application. The reason is simple, the images replaced by me are a few kb smaller, resulting in an application a little smaller than the one that I started with.

Why does a Titanium application take up so much space?

I had to do some searching before finding the answer. In 2011, when I first tried to research, I only found that all the libraries, needed or not, are packed inside and for this reason it takes up so much space. This wasn’t the cause! Meanwhile, I found the real reason. An application runs a “bridge” between Android and JavaScript. The source code is not “compiled”, as was the initial belief, but just interpreted.

The JavaScript code is interpreted using one of the available engines in the app (V8 and Rhino) and it calls other components that build the native graphing elements.

The issue is with the engines. They are quite big and are packed in every application. And, as if they weren’t large enough, there are 3 of them, each with its’ own purpose:

  • V8 – for newer Android version (after Gingerbread 2.3);
  • Rhino – for older Android versions (before Gingerbread 2.3);
  • x86 – for Intel processors.

These 3 engines occupy a total of 19M, unpacked on my computer. Thus, without eliminating some of them, we can’t get the app size to decrease.

One way Appcelerator is trying to tackle this size issue is to give up Rhino, breaking this way compatibility with older Android versions.

Community

There is a very active community. On the forums and Q/A platforms it’s full of questions and answers! I must admit that I was impressed in this aspect. Some questions are relatively old, even from 3 years ago.

Learning curb

For a week and almost a half, out of which almost a quarter I searched how to do a view moving effect, which in the end didn’t work, I must say it went pretty fast!

I must admit, I’ve played with it 3-4 years ago for a few days and I remembered a few things, like elements of type window, view and label.

The fact that I was able to find answers fast on questions about Stackoverflow, gathered in a few years, but also that the documentation is pretty well organized, helped a lot.

Also on Youtube there are some useful tutorials.

Development environment

In the first versions there wasn’t an IDE, the applications were written with an editor of choice, then packaged and tested using the platform.

Now there is an IDE based on Eclipse. The name is Titanium Studio. It has a pretty nice autocomplete, which helps in a lot of cases. It also has some drawbacks, like in my case sometimes the syntax highlight didn’t work, without any clue were the problem was. Also, project management seems a little strange and it had some issues with import and export of the projects.

There isn’t a default visual tool for editing elements in the page. Both Xcode and ADT allow for editing elements with drag & drop. It turns out there are tools for this, but they are not free.

Emulators are not very configurable. The good part is that you don’t have to worry, you select the operating system and display type and Titanium will automatically configure an emulator. The bad part is that I might wish for a clearer resource management.

Another disadvantage is that sometimes the application will crash before the emulator starts and if you try again it will try to start a new emulator without any luck, case in which the emulator has to be closed. Run Project clean and try again, careful not to miss the moment when the screen can be unlocked, or the scenario will repeat.

For iPhone logs do not work when it comes to OS X Mavericks.

Good parts

It is easy to learn.

The documentation is well done and where something is not clear, surely somebody asked the question before.

There is a fairly large community.

The IDE is easy to use.

It’s easy to see what is possible to achieve with the Kitchen Sink app.

The app doesn’t look like a web page in a WebView!

Bad parts

The app size is quite big (16M on the phone).

The graphical elements are only a subset of the platform.

It isn’t very fast, because the code is interpreted and not compiled, to be able to interact directly with the OS.

There isn’t a visual editor.

There are some issues on integration with emulators, both for Android and iPhone.

Conclusion

If you are a JavaScript connoisseur and you need an application fast and also want to have native graphical elements, then probably Titanium is for you.

If you want performance, probably you need to look for something else.

I don’t have enough experience with the Android SDK to be able to build this application in the timeframe I had available, this was my compromise.

To be honest, I’m not sure wether PhoneGap was a better option or not, speaking for my case. Today there are a lot of JavaScript libraries out there built especially to emulate native graphical elements into a PhoneGap application. The difference is not necessarily visible and, in the end, maybe sometimes the app doesn’t really have to look like a standard app, maybe a completely different interface is more appropriate.

Written by Claudiu Persoiu

24 December 2013 at 1:13 PM

Posted in JavaScript

Tagged with , ,

Building a new generation of programmers in a consumers society

without comments

Motivated by Rober Martin’s article, Hoards Of Novices, I’ve decided to write an article on a similar subject.

I do not want to write about the need for employers to hire juniors, but about why these juniors are not up to the expectations and, in the end, what can be done to be better prepared.

The software market is continuously expanding. Software is the way we command a computer what to do. Today, devices around us have processors, software and applications, from phones, watches, TVs and up to washing machines and refrigerators. All these devices need programms and programmers to develop applications for them.

With this premises, we reach the Software crisis. It was concluded that we need to build software faster in order to solve this crisis. This was a popular subject in the ’60s, but in time it has become less important.

To solve this problem, high level languages and frameworks were built. High level languages made development and maintenance of an application much easier. This way, programmers are getting very far from the “metal” of the actual hardware, working with concepts much easier to deal with.

In a world of high level languages (Java, C#, PHP, Python, JavaScript etc.) it is much easier and faster to create an application.

Yet, although developing an application is becoming easier, the quality of the developers is falling.

A consumer society

We need school for a better job.

Because the need for studies is a general need, the school itself is diluting. The educational principles haven’t had significant changes since education became available to everybody. The result of the learning process is the exam, in order to determine the level of knowledge. And even more, a mediocre result allows us to move forward, without prove that the required base is present.

Moving to the next level is done with a partial evaluation, you don’t have to know 100% of the information, just 50-60%. It is not exactly clear if there are important notions in the remaining 40-50%.

This educational problem is more or less a general problem and there are few those who try different approaches.

In general, I don’t consider school a defining system for determining the knowledge, especially today, when we have access to such a large volume of alternatives for it.

When students finish school, they don’t have all the required knowledge to actually work in the industry, which is not abnormal. School must offer a general basis. For instance, during my higher education I can remember at least 8-9 programming languages that we studied. There were actually more, but I didn’t keep a detailed evidence of them. It is clear that you can’t possibly know all these programming languages in order to become productive using them. On the other hand, you have an idea on how to approach them, which may help you to find the one you’ll like to study in thoroughness.

That’s the key, to study in thoroughness! For this we each have our approach, here you can find your own way, either courses, books, practical projects or all of them. By thoroughly studying a subject, the employers will not only accept you, but they will hunt you!

Often, the passion will totally replace the studies from school. I’ve met a lot of people which, even though they haven’t studied informatics in school, they are now professionals in it.

The good part is that a lot of people are studying from pleasure and I advise anyone who is reading these lines to search for pleasure in what they do. This is the best motivation.

Alternative education in a consumer society

Because the traditional learning techniques are no exactly sufficient, let’s talk about a few alternative methods:

  • books
  • courses
  • tutorials
  • articles/blogs

Books

Traditionally books are the best source of information (at least until the Internet became available). But there is no guaranty for the quality!

About 8-9 years ago I was trying to buy a JavaScript book. The selection wasn’t very big and so I tried to analyze each one.

In the end I was disappointed with my choice, because instead of teaching me JavaScript, the book was teaching how to make special effects on the page (very popular in that period).

In my particular case, I found the answer much later in a presentation by Douglas Crockford. He said that most JavaScript books are like that and he was recommending a single book, beside the book written by him, JavaScript: The Definitive Guide.

The reason is very simple, people tend to be more drawn by books that promise to teach a language or technology in a limited number of lessons or days. We want everything now, but studying takes time, you must understand the notions, not just a fast overview.

Generally, to determine the quality of a book you should look for reviews. These days it is very easy, I prefer Amazon.com and not only. This way you can determine if it is what you are looking for.

Sometimes a faster approach is useful, especially if you don’t have any previous experience on the subject, but generally this doesn’t offer a general perspective, only a gentile introduction.

Courses

There are a lot of courses, both in-class and on-line. Just like for the books, it is hard to determine the quality of the course.

Courses promise a lot, but a lot of the times they don’t treat the subjects in detail and in the end, even though you have the impression that you have learned a lot, when it comes to practice you realize that any variation from the course material is very difficult.

Just like for books, references are very important! Unfortunately, there aren’t as many reviews for course as there are for books.

Try to see what subjects the course is teaching and the detail of the approach. Sometimes, you can find more easily a reference for the teacher than for the course.

Tutorials

Especially on the Internet, there are a lot of tutorials that promise to teach a certain domain, but they only teach you how to create their example. In the end you can only create small variations of the initial example. Often, the creator of the tutorial has the best intentions, but it is hard to transfer information like this.

For the free ones it is very easy to determine if the approach is the right one for you and for your needs. Try to watch a few episodes and in the end see how much you’ve understood on how that particular component is working. If you can only replicate, maybe you need to search a little more.

The good part is that there are generally a lot of them to choose from. For instance, for a programming language you can first check the official reference to see what you should learn about, then in the tutorial you can see how many of the points from the reference were approached.

For the commercial ones it is a bit harder, because often you just have a small introspective preview, insufficient to form an opinion. For those particular cases you should search for reviews.

Blogs and articles

The good part here is that the time investment is relatively small. It is simpler to get a general idea.

The disadvantage is that some of the articles don’t update with time. You must make sure that the examples work on the version that you are using. From my own experience I can say that keeping an article up to date is hard an takes a lot of time. For instance some of the articles on this blog that still attract visitors are written a few years back and if I don’t use that particular technology anymore, I’m tempted not to keep them up to date.

How to learn better

Search for references and reviews for the materials that will require an investment in time and/or money: books, courses or tutorials.

When you’ve settled on a subject, try to see what materials others recommend. The Internet is full of materials of different levels of difficulty.

When you fell that you’ve mastered a subject, test your knowledge. Build an app, follow the subject on Q/A platforms or even write a tutorial for the others. You tend to understand much better a subject when you have to describe it to others.

Practice! It is very important to practice what you learn or you’ll forget much easier than you think. Contribute to open-source projects, try to do personal projects or try to adapt projects created by somebody else to your needs. Github is a very good tool for finding and publishing projects.

It is a bit harder at the beginning to understand somebody else’s code, but in the industry it is mandatory in order to be able to collaborate with others.

Learn new things all the time. Technology is changing, and so is the perspective over it. For instance, AJAX appeared in the late “90’s, but the perspective over it and how it can be used changed dramatically over the next few years, even though the technology itself didn’t change a lot during that time. The same for JavaScript, even though it appeared in the “90’s, only after 2000 it began to be considered an useful tool, previously it was mainly used for special effects on the page.

For a while, PHP was considered useful only for small projects. Today it is the language of choice for giants of the internet, like Facebook and Yahoo!. Along with the popularity, the best practices on the language itself changed for a better scalability and performance.

Conclusion

The educational system doesn’t offer the performance that employers are looking for. This creates a discrepancy between the expectations of the employers and those of the graduates, and this not restricted to informatics.

Unfortunately, the alternative materials sometimes also promise unrealistic things. Some study technologies and programming languages for months, while others promise results after only days or even hours.

Fortunately, we are living in an era dominated by information, and we can find not only materials, but also opinions about them.

Through better training, the changes of finding a job are rising considerably, resulting in satisfaction on both sides.

Written by Claudiu Persoiu

17 December 2013 at 11:18 PM

Posted in Diverse

Finally finally in PHP 5.5

with one comment

The newest PHP version is almost ready. At the time I’m writing this blog PHP 5.5 is in RC 1.

As I was saying in my last blog, the feature list is available at: http://www.php.net/manual/en/migration55.new-features.php

The second feature, in terms of popularity, is “finally“: http://www.php.net/manual/en/language.exceptions.php

What’s the deal with “finally“?

It looks a little confusing, is looks like a block that’s getting executed after the “try/catch” finishes. But what is so new about it?

Let’s take a try/catch block:

PHP 5.x < 5.5:

// open resouce
$resource = new Resouce();
try {
   // do stuff with the resouce
   $resouce->doStuff();
} catch (Exception $e) {
   // log exception
   syslog(LOG_ERR, $e->getMessage());
}
// release resouce
unset($resouce);

PHP 5.5

// open resouce
$resource = new Resouce();
try {
   // do stuff with the resouce
   $resouce->doStuff();
} catch (Exception $e) {
   // log exception
   syslog(LOG_ERR, $e->getMessage());
} finally {
   // release resouce
   unset($resouce);
}

Up to this point there isn’t any reason for a new block. The exception was catched, it was logged and continues.

But let’s say there is a resource and we need to close it, and after that we need to throw an exception. One way this can be achieved is to release the resource in catch.

But there is still the “successful” case, and we need to release it in that case also.

// open resouce
$resource = new Resouce();
try {
   // do stuff with the resouce
   $resouce->doStuff();
} catch (Exception $e) {
   // release resouce
   unset($resource);
   // perpetuate exception
   throw $e;
}

Let’s complicate stuff even more, let’s say there are n exception types. It will result in n catch conditions, plus the successful case, and in all of these cases we need to free the resource. Not very efficient…

Another way is to store the exception in a variable and, after the resource is released, to throw the exception, if that is the case.

// variable to store the exception
$exception = false;

// open resouce
$resource = new Resouce();
try {
   // do stuff with the resouce
   $resouce->doStuff();
} catch (Exception $e) {
   $exception = $e;
}

// release resouce
unset($resource);

if($exception) {
   throw $exception;
}

This is one way it is done right now. It’s working but it’s not clear that we are only trying to release the resource and continue our lives in peace.

The PHP 5.5 way

In the php.net manual:

In PHP 5.5 and later, a finally block may also be specified after the catch blocks. Code within the finally block will always be executed after the tryand catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.

Each time the block is executed, regardless if it was successful or not, finally will get executed. So, for the next example:

try {
    echo 'Do stuff' . PHP_EOL;
    throw new Exception('testing');
} finally {
    echo 'inside finally' . PHP_EOL;
}

The output will be:

Do stuff
inside finally

Fatal error: Uncaught exception 'Exception' with message 'testing' in...

If we want to also catch the exception:

try {
    echo 'Do stuff' . PHP_EOL;
    throw new Exception('testing');
} catch (Exception $e) {
    echo 'do something with the exception' . PHP_EOL;
} finally {
    echo 'inside finally' . PHP_EOL;
}

The output will be:

Do stuff
do something with the exception
inside finally

And even if we take the particular case when we catch the exception and then throw it:

try {
    echo 'Do stuff' . PHP_EOL;
    throw new Exception('testing');
} catch (Exception $e) {
    echo 'do something with the exception' . PHP_EOL;
    throw $e;
} finally {
    echo 'inside finally' . PHP_EOL;
}

It seems we prevented the finally block from getting executed? Well, not exactly…

Do stuff
do something with the exception
inside finally

Fatal error: Uncaught exception 'Exception' with message 'testing' in...

In other words, the finally block gets executed each time, regardless of the result.

Written by Claudiu Persoiu

19 May 2013 at 7:34 PM

Posted in PHP

Tagged with , ,

Generating generators in PHP 5.5

without comments

A new PHP version is about to be released. At the time I’m writing this blog PHP 5.5 is in beta 4.

Eager to see the updates, I’ve compiled the new beta version. The feature list is available at: http://www.php.net/manual/en/migration55.new-features.php

The generators are the most important feature..

Generating generators in PHP 5.5

A generator is basically a function that contains a call to “yield”.

Let’s take the example form php.net:

<?php
function xrange($start, $limit, $step = 1) {
   for ($i = $start; $i <= $limit; $i += $step) {
       yield $i;
   }
}

echo 'Single digit odd numbers: ';

/* Note that an array is never created or returned,
* which saves memory. */
foreach (xrange(1, 9, 2) as $number) {
   echo "$number ";
}
?>

Basically, the generator (xrange in this case), instead of returning an array, will return a value at a time, in order to be processed.

But wait… wasn’t this already possible before this version?

Generators before PHP 5.5

Before PHP 5.5 there were already Iterators:

<?php

class xrange implements Iterator
{
    private $position = 0;
    private $start;
    private $limit;
    private $step;

    public function __construct($start, $limit, $step = 1)
    {
        $this->start = $start;
        $this->limit = $limit;
        $this->step = $step;
        $this->position = 0;
    }

    function rewind()
    {
        $this->position = 0;
    }

    function current()
    {
        return $this->start + ($this->position * $this->step);
    }

    function key()
    {
        return $this->position;
    }

    function next()
    {
        ++$this->position;
    }

    function valid()
    {
        return $this->current() <= $this->limit;
    }
}

echo 'Single digit odd numbers: ';

/* Note that an array is never created or returned,
 * which saves memory. */
foreach (new xrange(2, 9, 2) as $number) {
    echo "$number ";
}
?>

Beside the fact that the Iterator is an object with multiple properties, basically we can achieve the same result.

But why do we need generators then? Simple! Instead of using ~40 lines of code, we can simply use 5 to achieve the same goal.

Another interesting thing is that:

get_class(printer());

will return Generator.

Basically, a generator returns an object of type Generator, and this object extends Iterator.

The major difference, as it is described on the php.net website, is that the generator can not be reset, basically it goes one way only.

Sending information to the generators

Yes, generators work both ways, but each generator only works in one particular direction. If the syntax above is for “producing” data, then the syntax below is only for “consuming” data.

The syntax for a “consumer” is simple:

<?php
function printer() {
    $counter = 0;
    while(true) {
        $counter++;
        $value = yield;
        echo $value . $counter . PHP_EOL;
    }
    echo ‘Never executed...' . PHP_EOL;
}

$printer = printer();
$printer->send('Hello!');
echo 'Something is happening over here...' . PHP_EOL;
$printer->send('Hello!');
?>

The output will be:

Hello!1
Something is happening over here...
Hello!2

Basically, the value of yield can be used as any other value. What’s interesting is the while. On php.net is the folowing comment:

// Sends the given value to the
// generator as the result of
// the yield expression and
// resumes execution of the
// generator.

The loop is needed because the generator will stop after it processes the value and will only continue when a new value is received. If we remove the while, only the first value will be processed, regardless of how many times we’ll call send().

An interesting thing is that what comes after the loop will not be executed, that is in my case:
echo ‘Never executed…’ . PHP_EOL;

So, if it looks like a good place to release a resource (e.g. DB or file), in fact it isn’t, because that code will never get executed.

It seems useful for logging. Again, nothing that couldn’t have been done before, but now it allows for an easier approach.

I’ve found though something that doesn’t work:

<?php
function printer() {
    while(true) {
        echo yield . PHP_EOL;
    }
}

$printer = printer();
$printer->send('Hello world!');

foreach($printer as $line) {
    echo $line . PHP_EOF;
}

A little chaotic, isn’t it? But I was wondering what would happen:
Fatal error: Uncaught exception ‘Exception’ with message ‘Cannot rewind a generator that was already run’ in…

So, once send() is used on an iterator, you can’t use it as an iterator again. Of course, another one can be generated with:
printer();

What is more confusing is that Generator is a final class, so it can’t be extended, and if you try to instantiate it directly (although even if it worked it would be useless):
Catchable fatal error: The “Generator” class is reserved for internal use and cannot be manually instantiated in…

Conclusion

It is an interesting feature because it simplifies things a lot when you try to create an iterator.

Also the use of send() seems very interesting, not because it is doing something new, but because it is doing it easier.

On the other hand, I don’t like that there is the same syntax for both generator versions and even more that what is after the while is not getting executed. I think the syntax is a little confusing because there isn’t a clear difference between the two. On the other hand, this already exists in Python, so for inspirator the examples from this language can be used.

Written by Claudiu Persoiu

10 May 2013 at 9:11 AM

Posted in PHP

Tagged with , , ,

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

Passing Magento Developer Plus certification

with 3 comments

Over an year ago, I started working on the Magento platform. In last year’s spring, a colleague from Optaros took the Magento Developer Plus certification exam. Since then, I began to like the idea of taking the certification exam, more as a motivation to learn the ins and outs of Magento.

Few months ago I was enrolled into a company study group for the certification. This was the first time I was sponsored for a certification (yes, until now everything was with my money). Preparing in a study group was a whole different experience.

Those who have more experience in a field balance the situation for the others and can give better examples from their own experience. It’s easier to understand from concrete examples then to try to imagine the scenarios yourself.

The certification is available through Prometric. So when you decide that you’re ready you can go to the website to purchase the voucher and schedule the exam.

The price for a voucher is 260$, not exactly cheap, but if you get to convince your boss to pay, it probably won’t be so bad. 🙂

But let’s get to the more interesting subject, the preparation.

Materials
Magento is not doing very good on this subject, there are very few materials and they are not centralized.

My sources were:
Magento® Certified Developer Plus Exam Study Guide – it is compulsive to read the guide and try to find answers to all the questions in it;
Magento training – especially Fundamentals of Magento Development
– blogs – I don’t want to give any names, there are a lot of people that write about the problems that they encounter and blog about the exam.

Unfortunately there isn’t a way like for PHP, ZF and Symfony where you can find all you need in one place, basically it depends on your luck and searching skills, there isn’t an “official version”. Things become weird when you find different approaches that are version specific.

How did I prepare
I began with the video training. It’s not perfect by it’s very helpful. I think the problem with most certifications is that you don’t get to work with all the available modules, just like in PHP you don’t get to work that much with sockets and streams.

Even though you don’t get the code and sometimes it is hard to follow and transcribe the examples, I think that the video tutorials are one of the most important sources at the moment.

Secondly, with the Study Guide in my hand, I began to try to answer the questions from it. When I joined the Study Group, the work divided between all the members in the group. My advantage was that it was the second generation of the group and we could profit from the documentation already developed by the first group.

If you’re preparing by yourself, I think the most important thing is to start, that’s the hardest part. And if you don’t know where to start, Google search the Magento questions, there are already a lot of people that are posting the explanations.

Answers for the questions from the first chapters are the easiest to find. As the number of the chapter is getting bigger, the number of Google results decreases.

But after the first questions, you should understand what is all about and in theory you will no longer need the documentation.

Use Mage::log(Varien_Debug::backtrace(true, false)); for stack trace and xdebug (http://xdebug.org/) to see what’s going on behind the scene. With patience, all the questions find their answers.

Because it was a group, the study was easier for me, but even so, to be sure of the explanation I has to dive deep in the code.

The exam
Some of the questions are difficult, but there are also accessible ones. The questions in the exam are off all levels of difficulty.

For Plus, the exam takes 2h not 2.5h as it is specified in the guide.

If you opted for Plus, there are 11 questions from Enterprise and advanced difficulty questions, of which 7 correct ones are required to pass. Basically this is the difficulty difference. For this questions it matters how much Enterprise experience you have.

In the guide for each exam, the questions are broken in percentages for each chapter.

Because in the non Plus certification there are no Enterprise questions, you only have to answer the necessary percentage from the full exam in order to pass and it’s not required to have a certain percentage from a certain chapter.

Things that are done regularly are analyzed in detail, it is important to understand how each function that is approached in each chapter works and what is the purpose of all those tags in the xml files.

Usually there are things you work with, or at least with which there is a good probability you have been working from the modules listed in the guide.

Post exam
Before you leave the room you’ll know if you’ve passed or not. When you exit the room you’ll receive a printed paper with the correct number of questions from each section from the total number .

In case you haven’t been successful you’ll receive by mail from Magento a voucher with a discount for a future attempt. They state that you should study at least 3 more weeks before you try again. Anyway, after you’ve taken the exam you’ll have a better view over your overall knowledge for a future attempt.

After few days (3 in my case) you will be able to see your profile on the Magento website as a reference.

The diploma got to Romania in about a month, the delivery address is the one from the Magento website account.

Best of luck!

Written by Claudiu Persoiu

16 February 2013 at 8:23 PM

Posted in Magento,PHP

Tagged with , , ,

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 , ,