To content | To menu | To search

Sunday 26 October 2008

PHP's april's fool

http://wiki.php.net/rfc/namespacese...

wait, we're not April 1st ?

Monday 14 July 2008

About the self keyword in static methods

While setting up a test server for some software I wrote at the office, I eventually noticed the following notice:

Notice: Use of undefined constant self - assumed 'self'

That surprised me, because 1) I though self were some kind of "superglobal" constant or a special token of the parser, always automatically available in a static method and 2) the code works. So what's up in there ? Let's make a simple test:

<?php

class foo {
	static public function bar() {
		var_dump(is_callable(array('self', 'foobar')));
		var_dump(is_callable(array(self, 'foobar')));

		var_dump(class_exists('self'));
		var_dump(class_exists(self));

		self::foobar();
	}

	static public function foobar() {
	}
}

foo::bar();

Executing the above code will yeld the following result:

bool(true)

Notice: Use of undefined constant self - assumed 'self' in /home/geoffreyb/test.php on line 6
bool(true)
bool(false)

Notice: Use of undefined constant self - assumed 'self' in /home/geoffreyb/test.php on line 9
bool(false)

What do we learn here ? Not much actually. It seems like self as a constant is only available when used with the scope resolution operator, aka double-colon or paamayim nekudotayim. When you want to use it in, for example, a callback definition, use a string representation of self:

<?php

is_callable(array('self', 'bar'));
call_user_func(array('self', 'bar'));

Which, while making absolutely no sense at all, works. Another way to get around this is to use the get_class() function that, without any argument, will return the name of the class you're currently in (foo in my example).

After a bit more investiging, I found out that there is nothing special about the self token, which is actually a string token. You can check this very easily with the following code:

<?php

class foo {
	static public function bar() {
		self::foobar();
	}
}

var_dump(token_get_all(file_get_contents(__FILE__)));

Somewhere inside the output, you'll find the following piece of text:

  array(2) {
    [0]=>
    int(307)
    [1]=>
    string(4) "self"
  }

And the token id 307 is resolved by token_name to string.

Monday 22 October 2007

How I use the Zend Framework

Having started a few applications using the Zend Framework, I came out with a few practices that I tend to use over and over. In this post I'll quickly expose some of them and explain why I do things the way I do them. As you'll notice, most of them are already widely known and used over the ZF developer's community. Please remember that these practices are just what I do, and come with no garanty at all to be best practices.

Continue reading...

Monday 1 October 2007

PDO not throwing an exception when it should

Today I ran into an issue that I already ran into a few weeks ago when I did not have time to dig up, but today I had this time (this plus it's a really annoying issue as you'll see). The main symptom is that PDO does not throws exceptions when you'd expect it to. It's very annoying. The reason, in my case, seems to be that I am querying an old mysql (3.23.x in my case but any 4.x will do according to this bug report). I was not able to find any info from google, so I'm posting this here so that people know :-)

New home for pagination component documentation

For those caring, I just posted some quick documentation for the pagination component at my assembla space. More docs will follow (including extensive phpdoc docblocks I hope).

Sunday 30 September 2007

Zend Framework 1.0.2 PEAR package is available

A PEAR package for the 1.0.2 version of the Zend Framework is now available from the PEAR PHPMafia channel. As usual, to install just issue the following:

pear channel-discover pear.phpmafia.net
pear install phpmafia/Zend

Bugfixes release of Zend Framework pagination component

I just released on riskle's assembla space a new version of my pagination component for the Zend Framework which you can download right now:

Riskle Paginate r122

This release fixes a nasty bug in Riskle_Db_Table::fetchCols which prevented from retrieving the right count of cols involved in the query.

The table component has also been slightly rewritten following Erik's suggestion to move the parent mapping into _fetch. The parent mapping itself has been improved to allow "multi level" table joining. This will be best explained with an example:

Say you have three table, Foo, Bar and Quux, and you would like to execute the following query:

SELECT * FROM Foo JOIN Bar ON Foo.bar_id = Bar.id JOIN Quux ON Bar.quux_id = Quux.id

This is now possible with the following mapping (in Foo's class of course):

array(
    'Bar' => array('local' => 'bar_id', 'remote' => 'id'),
    'Quux' => array('local' => 'quux_id', 'remote' => 'Quux.id'),
);

Easy heh ?

As usual, any comments are appreciated, and please note that this code is released under the same license as the ZF itself, the new-bsd license.

Sunday 23 September 2007

Zend Framework Pagination, third strike

UPDATE: new version (r105) available.

The component was given a little rewrite as expected, but maybe a little bit later than I would have wanted to :-) So it now has its own Rowclass proxy from which you can pull various infos such as current page, page range, next page, etc all exposed as getter methods (that is, getCurrentPage, getPageRange, getNextPage, etc), which you won't really have to worry about since the brand new view helper will take care of that for you. Usage has changed a little, bit, so let's first have a look at what's happening from the controller point of view:

$table = new Riskle_Db_Table_Paginate(new Table, $this->_getParam('page'));
$this->view->rowset = $table->fetchAll();

Not much changed here, except we don't need anymore to call getPaginationInfos(). Nice ! Now the big part, the view:

$this->paginate($this->rowset);
echo $this->paginate()->previous();
echo $this->paginate()->navigation();
echo $this->paginate()->next();

The view helper uses the neat composite helper trick from naneau - which is a really cool trick, great job naneau my fellow no-more-a-bunny. The first call inits the helper, feeding him the necessary rowset to work on, then you just have to call the methods you need to draw the navigation links. As you may expect, previous and next method will return nothing if no page is available (actually, they return their second argument, which defaults to an empty string).

Also, it's worth noting that the bundled Riskle_Db_Table features the patch from Erik, as well as a totally rewritten fetchCols method (now uses a straight Zend_Db_Select object instead of the ugly trick it used to use).

My code is no longer available on subversion, I moved the project to assembla. Instead ou can download this component from the riskle space's files board (direct download), the file contains all classes needed for the component to work, just unzip it in your include_path and you're set.

As usual, any comments are more than welcome.

Wednesday 19 September 2007

Riskle_Form, a quick wrapup

So well, I've been busy these days working on my own implementation of a form component in the ZF spirit. This post is to help me see where I'm at with this component, as well as planning future evolution. I'll try my best to describe what it does and does not, and what it could do in the future.

Of course, while this is more of a personnal pense-bete than anything else, any comments are welcome.

Continue reading...

Thursday 30 August 2007

Quick php5 pre-migration check

If you're wondering how much of a hassle it would be to migrate your app / codebase to php5, try the following command line (after having installed the php5-cli package of course):

find . -name "*.php" -exec /usr/bin/php5 -l {} \; | grep -v 'No syntax errors'

It'll show you all the files with syntax errors in it.

Tuesday 14 August 2007

findBy{$Field} with Zend_Db_Table

A quick post to show how one can easily implement a findByField wrapper in Zend_Db_Table:

/**
         * Implements a simple findByField wrapper
         */


        public function __call($method, $args) {
                if (preg_match('/^findBy([a-zA-Z0-9]+)$/', $method, $parts)) {
                        $field = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $parts[1]));
                        if (!in_array($field, $this->_cols)) {
                                throw new Zend_Db_Table_Exception(sprintf('\'%s\' field not in row', $field));
                        } else {
                                $db = $this->getAdapter();
                                $where = $db->quoteInto($db->quoteIdentifier($field).' = ?', $args[0]);
                                return $this->fetchAll($where);
                        }
                }
        }

What it does is basically trapping any non-existant method call and check if the corresponding field exists, after converting CamelCasing to underscore_notation (eg: FooBar becomes foo_bar).

Saturday 11 August 2007

Stripping the logic: the Transfer Object

Sometimes you have to pass an object data to another object, or to another layer of your application (who said controller/view ?), while ensuring that the receiving entity will not be able to run business code encapsulated in your class. In the Zend Framework, several objects provide a toArray method, but that is not always sufficient as sometimes you'd like to keep with the $object->varname syntax.

That is where the Transfer Object arrives. While the preceding definition is not exact (that's not the real purpose of the Transfert Object in the J2EE spirit), This is the most common use that PHP Developers can make of it nowadays I think. So I came up with a very light implementation of a concept which I hope can prove useful for any folks getting by there.

See also:

Tuesday 31 July 2007

Zend Framework Pagination reloaded

UPDATE

A new version of this component is available.

I have a new version of my pagination component which solve the issue previously pointed out by Guy. This update comes along with a subclassed version of Zend_Db_Table which allows counting and specific columns selection respectively via the fetchCount() and fetchCols() methods. Btw, the fetchCols() method is very hackish at the moment, and I'll certainly end up with rewriting it using a plain Zend_Db_Select statement.

As always, any comment is appreciated. I'm thinking of subclassing the Rowset class to fill it with pagination info getters like getPageCount(), getNextPage(), etc, like in Symfony for those knowing, instead of relying on a getPaginationInfo() method. Future improvements will also include more view helper magic.

Also, I came up with a small new Riskle_Pattern namespace which I use to implement commonly used patterns, such as the Proxy Pattern. I'm not yet sure of the pertinence of this thing, so any comments are yet again very much appreciated on this topic :-)

Thursday 19 July 2007

Searching the Zend Framework's manual: Google Co-op to the rescue

While the Zend Framework's manual is somewhat quite good, it lacks a feature that make it a really good manual: search. I find it very frustrating to not be able to make a simple search and therefor having to browse through the extensive TOC to find what I'm actually looking for. Here enters the very handy Google co-op service which allows creation of custom search engines based on Google's indexes. It do not takes more than five minutes to setup a simple search engine, thus providing search capability to the manual :-)

And as a good news never comes alone, I also made the OpenSearch plugin for it.

UPDATE

I made a simpler url to remind of: http://zend.riskle.com/search/ and updated the opensearch thing to use that url.

Sunday 15 July 2007

Pagination with the Zend Framework

Yesterday I came up with a small pagination component for the Zend Frameworks. It implements the Proxy pattern around a Zend_Db_Table object, and overloads the fetchAll method. The main problem I encountered here was to retrieve the total number of rows for the table. I'm using a Zend_Db_Select query for now, but I'll have to improve that. The component also features a view helper to draw the pagination links.

You'll find the code for the component and the view helper on my SVN.

And here is how it is used in the controller:

    public function indexAction() {
        $urls = new Riskle_Db_Table_Paginate(new Urls, $this->_getParam('page'));
        $this->view->urlsList = $urls->fetchAll(null, 'datetime DESC');
        $this->view->paginationInfos = $urls->getPaginationInfos();
    }

The view helper takes paginationInfos as an argument:

echo $this->paginate($this->paginationInfos);

UPDATE

As pointed out by Guy, the _getPageCount method does not actually takes care of the $where condition, thus rendering the class inefficient as getting the real totel number of items. This issue will be adressed in an upcoming version of the class :-)

UPDATE

There's an updated version of this component available.

Saturday 14 July 2007

A Zend controller plugin to enable RESTful behaviour

This is a simple controller plugin for the Zend Framework which enable RESTful behaviour. It basically adds the HTTP method name to the action name, so that the URL http://example.com/foo/bar will be dispatched to FooController::barGetAction on a GET, FooController::barPostAction on a POST, etc.

Continue reading...

Sunday 1 July 2007

Get the current $view from a view helper

So you're making your own view helper and you need, for a reason, to access the running $view instance. Don't worry, all you have to do is implement a setView() method which will be called on your helper's instantiation, with the $view as argument:

class My_View_Helper_SpecialPurpose {
	
	protected $_view = null;
	
	public function setView($view) {
		$this->_view = $view;
	}

}

And voila !

Monday 25 June 2007

Zend Framework 1.0.0 RC3

Allez hop, la RC3 du Zend Framework est sortie (il y a 2 jours).

J'en profite pour faire un peu de pub pour zftalk, un chan IRC sympa.

Wednesday 13 June 2007

Zend Framework 1.0.0 RC2

Au fait, j'ai mis en ligne le package pear de la 1.0 RC2 du Zend Framework hier, avec un peu de retard donc, puisque j'étais occupé à imiter les oiseaux :)

Monday 7 May 2007

Zend Framework 0.9.3

Dernière ligne droite avant les premières 1.0 RC, la beta 0.9.3 du Zend Framework est sortie, et son package est disponible sur le channel PEAR PHPMafia.

- page 1 of 3