Evert PotPHP's callable typehint too loose? (6.5.2015, 17:03 UTC)

PHP got support for closures in version 5.3, and in PHP 5.4 we got support for a callable typehint, that can be used as such:


function callMe(callable $callBack) {




All these little changes make it feel more comfortable to apply functional programming concepts to PHP, but occasionally we need to drop back to using less aesthetically pleasing code.

To use our callMe function to call back directly to a object method, we use this syntax:

callMe([$object, 'method']);

This also works with static methods:

callMe(['\\Namespace\\MyClass', 'method']);

Or if you are on PHP 5.5:

callMe([MyClass::class, 'method']);

These all work, because when you execute this code:

$foo = [$object, 'method'];

...PHP will actually correctly execute method on our $object. But there's an exception. Aside from the previous syntax for calling static methods, PHP also allows this to fulfill the callable typehint:


Unfortunately, this will trigger the following error:

Fatal error: Call to undefined function MyClass::method() in /in/Kkr3F on line 14
Process exited with code 255.

The only remedy is to change our original function from:


function callMe(callable $callBack) {






function callMe(callable $callBack) {




call_user_func($callBack); does what $callBack() does, but it's less aesthetically pleasing.

So if you rely on the callable typehint, or the is_callable() function, be aware that you need to use call_user_func() to get reliable results.


I came to write this because I got a bug report from someone who wanted to be able to use the 'MyClass::method' syntax. I was a bit surprised this didn't work, as I had always used ['MyClass', 'method']. So, before changing all my $x() to call_user_func($x), I first had to figure out how this was possible.

What do you think? Is this a PHP bug? Or was I wrong to think that this should have worked in the first place?

SitePoint PHPSymfony2 Pre-registration and Invite System (6.5.2015, 16:00 UTC)

We have discussed Symfony 2 development in previous SitePoint articles and we built a clone of my own personal Symfony app (Part 1, 2 and 3). But Symfony 2 is a gigantic framework and there are plenty more topics we can cover.


In this article series of two parts, we are going to talk about a very important area of web application development: Authentication and Authorization. Symfony2 has a very detailed elaboration of these two topics in its official documentation. Anyone who is seriously looking into this is encouraged to read through that official document after absorbing the essentials from this tutorial.

A typical User Management flow may have the following tasks:

  • A built-in user will be generated upon application installation and will be granted the root equivalent privilege.
  • Any new user can either register via a form or can only register via invitation (which is the approach discussed in this article).
  • After registration, a user record is stored into the underlying database/table.
  • Optionally, the app will put this new user in a “pending” status and send out a confirmation email. A user will only be “activated” when they click the link in the email with a confirmation token. This approach is not used in this article because we are inviting users and the site is a “closed circle” site.
  • A user logs in. The app will verify the user name and password.
  • Optionally, the app can do some post-login activities. In this case, we will update the user’s last login date/time in the database, and redirect them.
  • The user can explicitly choose to logout.

The underlying user table

Although Symfony supports in-memory user authentication, that is not recommended in a real-world application. Most of the time, we’ll tap into other resources (database, LDAP, etc) to persist the user credentials. We will use an SQL database in our app.

Continue reading %Symfony2 Pre-registration and Invite System%

PHP ClassesHave Your PHP Book Reviewed (6.5.2015, 09:06 UTC)
By Manuel Lemos
The PHP Classes site is reviving its sections for book reviews and tutorial articles. This is an initiative to give more exposure to the work of those that can teach the PHP developers sharing their knowledge about important subjects.

The PHP Classes site book reviews and blog articles are notified by email to over 400,000 PHP developers. This initiative is a great opportunity for authors to expose their work to the PHP community at large.

Article authors and book reviewers may also receive be rewarded either monetarily or by getting free review book copies provided by their publishers.

Read this article to learn how you can have your PHP book reviewed, or you can publish interesting blog articles and be compensated for sharing useful knowledge with the PHP community.

If you are a book publisher you should also read the article to learn how you can reach out to have reviewed in PHP Classes site books of the interest of the PHP community.
Davey ShafikSpeaking at phpDay 2015 (6.5.2015, 01:47 UTC)

I will be returning to Verona for phpDay 2015 in just a few weeks to give two presentations, Writing Faster PHP with HHVM & Hack, and a new talk on PHP 7:

What to Expect When You’re Expecting: PHP 7

PHP 7 is coming, and with it will come new features, backwards compatibility breaks, and huge performance gains.

This talk will get you prepared for all the changes in this upcoming release and offer practical advice you can implement now to ensure you code still works come upgrade time.

I’m excited to give my first talk on PHP 7, and excited to go back to Verona — if you have the opportunity to get there, it’s a beautiful city, with wonderful people, and don’t forget to sample the amazing Gelato!

Hopefully I’ll see you there!

Brandon SavageCreating services you won’t hate (5.5.2015, 12:00 UTC)

The biggest complaint people have about object-oriented design is where they put all the “glue code” that ties together a bunch of objects and makes them work well. For many, this place is the controller, but as I’ve covered before, most of this logic belongs in the model. In fact, the model should be where […]

The post Creating services you won’t hate appeared first on BrandonSavage.net.

Michelangelo van Dampopen for cli commands and pipes in php (5.5.2015, 11:30 UTC)
Source: Pipes 1/3 by Jonah G.S. on Flickr.com
I got a question today about using commands that pipe output to other commands within PHP applications.

There are two functions in PHP that are perfect for the task: popen and proc_open.

The function "popen" opens a process file pointer, basically you have a pointer during the execution of a process. This functionality is often useful when you have one-way traffic (like piping commands on command line).

The function "proc_open" behaves the same as popen, but gives you access to the input and the output, which makes it very useful for reading and writing as you go along.

So let's say you have logic that generates a crontab entry, you can always do this using the commandline.

/usr/bin/php crontab.php | /usr/bin/crontab
But when you want to run it as a complete process, you can go about using exec, shell_exec, passthru or system and fiddle with escapeshellcmd. But often this looks messy and not reusable.

A better approach would be to use "popen". A small example would look something like this:


$output = '*/5 * * * * /bin/echo "Hello World!" 2>&1' . PHP_EOL;
$command = '/usr/bin/crontab';

var_dump(cmdPipe($output, $command));
* Functionality to pipe output
* @param string $input The command that needs to be executed
* @param string $commandline The command the first command needs to be
* piped to
* @return string The output of the given command
* @throws \RuntimeException
function cmdPipe($input, $commandline)
if (false === ($pipe = popen("echo \"$input\"|$commandline", 'r'))) {
throw new \RuntimeException('Cannot open pipe');
$output = '';
while (!feof($pipe)) {
$output .= fread($pipe, 1024);
return $output;
DISCLAIMER: This is not secure code and should not be used as-is in production environments!

Build it as a feature element and you now have a piping functionality you can nest, embed but most of all: reuse.
Cal EvansIt’s the Booze Talking – The PHP Ecosystem (5.5.2015, 05:00 UTC) Link
Nikita PopovInternal value representation in PHP 7 - Part 1 (5.5.2015, 00:00 UTC)

My last article described the improvements to the hashtable implementation that were introduced in PHP 7. This followup will take a look at the new representation of PHP values in general.

Due to the amount of material to cover, the article is split in two parts: This part will describe how the zval (Zend value) implementation differs between PHP 5 and PHP 7, and also discuss the implementation of references. The second part will investigate the realization of individual types like strings or objects in more detail.

Zvals in PHP 5

In PHP 5 the zval struct is defined as follows:

typedef struct _zval_struct {
    zvalue_value value;
    zend_uint refcount__gc;
    zend_uchar type;
    zend_uchar is_ref__gc;
} zval;

As you can see, a zval consists of a value, a type and some additional __gc information, which we’ll talk about in a moment. The value member is a union of different possible values that a zval can store:

typedef union _zvalue_value {
    long lval;                 // For booleans, integers and resources
    double dval;               // For floating point numbers
    struct {                   // For strings
        char *val;
        int len;
    } str;
    HashTable *ht;             // For arrays
    zend_object_value obj;     // For objects
    zend_ast *ast;             // For constant expressions
} zvalue_value;

A C union is a structure in which only one member can be active at a time and those size matches the size of its largest member. All members of the union will be stored in the same place in memory and will be interpreted differently depending on which one you access. If you read the lval member of the above union, its value will be interpreted as a signed integer. If you read the dval member the value will be interpreted as a double-precision floating point number instead. And so on.

To figure out which of these union members is currently in use, the type property of a zval stores a type tag, which is simply an integer:

#define IS_NULL     0      /* Doesn't use value */
#define IS_LONG     1      /* Uses lval */
#define IS_DOUBLE   2      /* Uses dval */
#define IS_BOOL     3      /* Uses lval with values 0 and 1 */
#define IS_ARRAY    4      /* Uses ht */
#define IS_OBJECT   5      /* Uses obj */
#define IS_STRING   6      /* Uses str */
#define IS_RESOURCE 7      /* Uses lval, which is the resource ID */

/* Special types used for late-binding of constants */
#define IS_CONSTANT 8

Truncated by Planet PHP, read more at the original (another 36140 bytes)

Matthew Weier O'PhinneyPSR-7 By Example (4.5.2015, 21:40 UTC)

PSR-7 is shaping up nicely. I pushed some updates earlier this week, and we tagged of the http-message package last week today for implementors and potential users to start coding against.

I'm still hearing some grumbles both of "simplify!" and "not far enough!" so I'm writing this posts to demonstrate usage of the currently published interfaces, and to illustrate both the ease of use and the completeness and robustness they offer.

First, though I want to clarify what PSR-7 is attempting.

HTTP Messages

HTTP messages are relatively simple, which is why the protocol has succeeded over the years. All messages have the following structure:

<message line>
Header: value
Another-Header: value

Message body

Headers are key/value pairs. The keys are case insensitive. Values are strings. The same header type may be emitted multiple times, in which case (typically) the values are considered as a list; in most cases, these can also be expressed by concatenating the values with comma delimiters.

The message body is a string, but typically handled by servers and clients as a stream in order to conserve memory and processing overhead. This is incredibly important when you transmit large data sets, and particularly when transmitting files. As an example, PHP natively represents the incoming request body as the stream php://input, and uses output buffers — a form of stream — to return a response.

The message line is what differentiates a request from a response.

The message line of a request is called the request line, and has the following format:

METHOD request-target HTTP/VERSION

METHOD indicates the operation requested: GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD, etc. The VERSION is typically 1.0 or 1.1 (usually 1.1 in modern web clients). The request-target is where things get complex.

A request target can be one of four different forms:

  • origin-form, which is the path and query string (if present) of the URI.
  • absolute-form, which is an absolute URI.
  • authority-form, which is the authority portion of the uri (user-info, if present; host; and port, if non-standard).
  • asterisk-form, which is the string *.

Typically, an HTTP client will use the scheme and authority from a URI to make the connection to the HTTP server, and then pass an origin-form target in the transmitted HTTP request message. However, it's perfectly valid to send the absolute URI as well. authority-form is typically only used with CONNECT requests, which are usually performed when working with a proxy server. asterisk-form is used with OPTIONS requests to get general capabilities of a web server.

In short, there's a lot of moving parts in the request-target.

Now, to make things more complicated, when we look at URIs, we have the following:

<scheme>://<authority>[/<path>][?<query string>]

The scheme, when doing HTTP requests, will be one of http or https. The path is a well-known format as well. But what about authority?


The authority always contains the host, which can be a domain name or an IP address. The port is optional, and only needs to be included if it's non-standard for the current scheme (or if the scheme is unknown). user-info is of the form:


where password is optional. In fact, in current specifications, the recommendation is to never include the password in a URI, to force prompting for the value by the client.

The query string is a set of key-value pairs delimited by ampersands:


Depending on the language implementation, it can also model lists and hashes:


PHP will parse the above to:

    'sort' => [
    'filter' => [
        'product' => 'name'

Truncated by Planet PHP, read more at the original (another 29228 bytes)

SitePoint PHPAutomatic PHP Code Generation with Memio (4.5.2015, 16:00 UTC)

Ever thought of writing code responsible for generating certain PHP classes, methods, properties automatically? Read on to get the details on when exactly automatic code generation may be helpful and - what’s most important - how to implement it properly using the Memio library.

Code Generation Hero Image

The Concept

The basic idea is quite simple. You write code which will create other parts of the code, functions, variables, classes, doc blocks, etc. As you do it in a programming language (PHP in our case), you can specify parameters, if-else statements, loops, and so on.

Of course, being able to create PHP code automatically doesn’t mean we, the developers, will be replaced. But it may be used to form a basic structure which will later be further developed by a human. For example, instead of copy-pasting to prepare an initial set of classes in your application, you can use a generator.

Code generation is already being used in various frameworks. See Symfony2 GeneratorBundle, CakePHP console commands or Laravel Artisan for examples.

Continue reading %Automatic PHP Code Generation with Memio%

LinksRSS 0.92   RDF 1.
Atom Feed   100% Popoon
PHP5 powered   PEAR
ButtonsPlanet PHP   Planet PHP
Planet PHP