This seems kind of limitation to me, indeed, if you use __toString() magic method for anything other than simple object variables concatenation, your code should be able to throw exceptions. Consider you have an object that generates XML as output, and you decide to provide even nicer interface, so that anyone using it in string context to get access to that XML. XML generation might not go well, and the obvious way to let the client know about this is to throw an exception. However, this is not possible (most probably due to some internal architecture limitations – as I honestly see no reason why this ideologically wrong).

One (not quite pretty) way to still provide some feedback from __toString() is using trigger_error:

public function  __toString()
{
    try {
        $output = $this->generateXml();
        return $output;
    } catch(Exception $e) {
        trigger_error($e->getMessage(), E_USER_ERROR);
        return '';
    }
}

If you know of a better option, let me know!

,

Starting with PHP5 almost any PHP installation contained SPL (Standard PHP Library) extension – with few exceptions, when hosters intentionally disabled it. With PHP 5.3 out, this extension is considered to be within PHP core, and as such it’s not possible to disable it anymore. This in fact is a good thing, as SPL really deserves to be the core component.

In an attempt to shed some light on and to draw attention to SPL, I plan to post several articles discussing various parts of this extension. I will start with SPL Interfaces so that you can grasp immediately the usefulness of the SPL.

Comprehending SPL interfaces presupposes that you know standard interfaces that come build-in with PHP5. So, I wrote preliminary article discussing them – I consider it to be a prerequisite for good understanding of the current material.

Covered in this article:

Read the rest of this entry

, ,

Note: This article serves as preliminary for SPL Interfaces article to be published later on.

I wanted to provide good overview of (highly under-used) Standard PHP Library (SPL) starting with interfaces. However, without firstly discussing predefined interfaces, which come bundled with each and every PHP distribution, discussion of SPL-provided ones seemed to be incomplete.

To be covered in this article:

Read the rest of this entry

, ,

Rendering view script for particular controller action is really easy. Indeed, thanks to (enabled by default) ViewRenderer helper, scripts are auto-loaded: renderer searches script directory(ies) for a view script called CONTROLLER_NAME/ACTION_NAME.SCRIPT_EXTENSION once found, view is auto-rendered.

However, sometimes it’s not what you want, instead you need to render some other view depending on some internal criteria. For example, you may want to render some custom error displaying view. So, if we are positive on what we want, let me show you how to do it:

class TestController extends Zend_Controller_Action
{
    /**
     * test/index.phtml would be rendered by default
     * @return void
     */
    public function indexAction()
    {
        // render test/foo.phtml
        $this->_helper->viewRenderer('foo');

        // render bar/foo.phtml to the default response segment, without using a
        // controller view script subdirectory ("test" in this case):
        // so you may use scripts from other controllers
        $this->_helper->viewRenderer('bar/foo', null, true);

        // now render the script, as previous calls do not render anything,
        // they are just used so that default script is swapped and not rendered:
        $this->render('foo');
        // OR
        $this->render('bar/foo', null, true);
    }
}

Please, note that you do not need to provide view extension (foo but not foo.phtml or any extension you happen to use for your views) – what renderer expects is action name, and we simply swapping the current action. Internally, direct() method is called when you update view renderer, which in turn is proxy for setRender():

// allows you to set any of scriptAction, responseSegment,
// and noController in one pass.
setRender($action = null, $name = null, $noController = false)

So, you may use

$this->_helper->viewRenderer->setRender('foo');

to change current view, but this form is less common, as it requires more typing :)
NB: If you need more info on ViewRenderer there’s no better place but ZF Manual.

Sometimes, especially when dealing with variations of factory pattern, single method (namely factory()) can return objects of different types, so NetBeans is unable to guess the exact type of returned instance and as such cannot auto-complete. Indeed, you can setup return type using phpDoc syntax:

/**
 * @return Some_Base_Abstract_Class_Name
 */
public function factory($adapter)

but that doesn’t work if returned objects are specifications of more general abstract class (exactly the case with factory).

As it turned out, you can easily resolve this issue – just document your variable with @var, before calling factory() method:

/**
 * @var Some_Specific_Class $foo
 */
$foo = Magic::factory('adapterName');
$foo-> // and NetBeans opens pop-up list with available attributes and methods

The good news, you can use this method in any scope – it just works :) I love NetBeans!!

UPD: Well, actually NetBeans seems to be picky of scope – as reported by others (and confirmed by myself).

UPD1: Actually NetBeans handles this quite well, just use vdoc (review this and this for details)

,

Today, when working on UMapper plugin, I tried to use jQuery – and failed. Although jQuery is now in WP core, $ shortcut wasn’t working. As it turned out, WP team (quite rightly!) used JQuery.noConflict – which helps avoiding naming conflict with similar libraries, such as prototype. So, we cannot use $ shortcut function, which is quite annoying. In order to overcome this limitation the following construct can be used:

jQuery(document).ready(function($){
    // inside this block you can use $ shortcut !!
});

Just a small note to myself :)

,
WARNING: this post is outdated.
Zend Framework has resource autoloading, so I keep the post for historical reasons only.

Zend Framework (ZF) is the MVC framework. Of course you can use its components in a non-MVC way (and I actually do so in my WP UMapper plugin), but in that case, I suppose, you do not have to worry about models auto-loading.

Frameworks make our coding life easier, and ZF is not an exception – you need very little code to get your application skeleton working. And when it comes to MVC, ZF handles almost everything – your action controllers are triggered, your views are loaded, w/o you having to worry about them. Not the same with models. If you comply to directory layout advised by ZF, you have “models” folder, but framework doesn’t interact with it in any way.

Models are simply classes, containing application logic, and to initialize one of them you have to make sure that:
a) containing directory is withing include_path
b) you require_once the class file before using it

I wanted my models to be available without any additional hassle, so I decided to find a way to auto-load models from within my controller actions.

Read the rest of this entry

, ,

It’s been several days that I am relying solely on NetBeans for my PHP and Java coding. So far, it’s beyond my wildest expectations – I am totally satisfied with that great IDE. Today, I have searched for shortcut that would allow me to duplicate a given line, and (fortunately!) came by a great post – Top 10 NetBeans IDE Keyboard Shortcuts. Not only I found the line-duplication thing, I discovered several other pearls which due to unavailability in my previous IDEs, I even didn’t consider to look for.

So, I decided to compile my own list of shortcuts that save me a lot of time during code-sessions.

Shift + Esc Toggle Work-space Maximize/Minimize

Like the original post author, I really like to have as much work-space available for code itself as possible. And when I occasionally need to see one of the supplementary panels (like Files, Project, Navigator etc), I rely mostly on short-cuts, w/o toggling back. So, if I need to view some docking panel I hit one of the following:

Ctrl+1 – Project Window
Ctrl+2 – Files Window
Ctrl+3 – Favorite Window
Ctrl+4 – Output Window
Ctrl+5 – Services window
Ctrl+6 – Tasks Window

and when I am done, Ctrl+0 to get me back to editor. Try for yourself, I am pretty sure, you’d be amazed how much time this saves you, while making coding area less cluttered.

Alt+Enter View fix suggestions

NetBeans makes your life a lot easier, its Java code analyzer does a really solid job. Most of errors are filtered even before compilation – should you see the light bulb on the left of your code, you can review fix suggestions by either clicking on it or (time-saver again!) by just hitting Alt+Enter. I personally enjoy this one, as I prefer to see why IDE is complaining w/o releasing my hands of the keyboard.

Ctrl+F12 Navigate to Member

If your class is too big, then Members View in Navigator (Ctrl+7 remember?) might not be the best option. Just hit Ctrl+F12 and you’d be able to navigate more easily, as it has filter that would eliminate non-matching members while you are typing.

Alt+Insert Generate code

That’s one of my favorites – code generators for getters/setters/constructors are just too sexy to ignore. This shortcut makes them even more usefull.

Ctrl+Shift+ArrowDown Duplicate Line

Duplicating lines never been easier :) If you want a new duplicate to be inserted before the current line, use ArrowUp instead of ArrowDown.

Ctrl+W Close Current Window

Firefox honors this short-cut, as well as Konqueror. So, I even configured my console to use this by default. In no time you’d be accustomed to hit this combination instead of Ctrl+F4.

Ctrl+PgUp and Ctrl+PgDn Navigate through Windows (previous/next)

Again, got used to it from Firefox. Makes it a swift to loop through open documents.

Ctrl+P Display method’s arguments

Within method’s braces hit this combination to see what parameters are there. Comes where handy when reviewing the code.

Ctrl+; Add semicolon to the end of the line w/o leaving current cursor position

If you are working on some code line and NetBeans underlines it red (due to [yet] non-existent semicolon at the end of the line) hitting Ctrl + ; (Ctrl + semicolon) is enough to close the statement, while you are still positioned at the very same place on line. First saw this on dzone.com blog, and really liked using it.

Ctrl+K and Ctrl+L Auto complete with previous/next matched word

I use this combination even more often than Ctrl+Space to auto complete. Listing all items with Ctrl+Space might be slow, but hitting Ctrl+K is instant. More than often the variable name you are typing is already typed somewhere in the current file, thus matching it with Ctrl+K or Ctrl+L is probably most obvious thing to do.

Ctrl+E Delete current line

Ctrl+Del and Ctrl+BackSpace Delete next/previous word

I generally use Ctrl+BackSpace, but on some occasions Ctrl+Del also proved userful.

That’s more than enough to get you going. In some time, I plan to write more extensive list  of esoteric shortcuts you rarely use, because you rarely know about them.

And what shortcuts save your time?

,

This category would contain English feed of phpmag.ru blog.

В случае когда определенные файлы/каталоги не должны попадать под контроль версий, достаточно установить свойство svn:ignore:

svn propset svn:ignore *.pyc dirname

В случае если такое свойство уже существует:

svn propedit svn:ignore dirname

Например, на UMapper‘е для игнорирования авто-сгенеренных CAPTCHA файлов находящихся в каталоге /files/captcha и имеющих названия вида “cap_RANDOM_STRING”, я использовал следующую комманду:

svn propset svn:ignore cap_* /files/captcha/
,