I made a bunch of extensions to CHtml that I reuse across projects - and for each project, I derive a class from that, with project-specific Html extensions.
I’m discovering some ugly limitations of static classes in PHP.
Let’s say static class X extends B - so B is the base class, and X is the extension class.
If X overrides a static member, say, $var, of class B, the new value becomes inaccessible from B. As a work-around, the PHP team added late static binding - so you can use the static::$var syntax, as an alternative to self::$var - which will enable you to access the overridden X::$var from class B.
Unfortunately, this approach isn’t much better, since if X does not override $var, static::$var will fail in B.
In other words, the whole thing is sort of dodgy, and I don’t think the majority of developers even fully understand the meaning of late static binding.
There are other problems with static classes, but without getting into this, I’d like to suggest a way to avoid this in Yii 2.0, by turning helpers into real application components - which would also enable us to configure them.
Now, some of you are going to frown at this, but here it is…
<?php
function html()
{
return Yii::app()->getComponent('html');
}
Yes, a flat function.
Now, in your views, you can say html()->beginForm() rather than Html::beginForm() … which, if you try it out, is actually easier to type, too.
Why would I advocate such a thing?
The thing I’m thinking is, flat functions make up the majority of PHP itself - which is the platform you’ve chosen. You’re not likely to run more than one framework at a time, and you’re not likely to write your own flat functions if you’re writing a Yii application. That means the global function namespace isn’t being used for anything at all.
So why would it not be okay for the framework to give you shortcuts, in the form of functions in the global namespace, for things like helpers? I don’t see a problem with that at all. You’d merely be using a namespace that isn’t useful for anything else, anyway.
I also would advocate shortening Yii::app() to simply app(), and Yii::app()->getUrlManager()->createUrl() to url() - as these functions would simply map to their OOP counterparts, you’re not losing any flexibility or functionality, you’re just getting a nicer, shorter syntax for the most commonly used features.
The fact of the matter is, the global namespace is there - it’s an integral part of PHP, and it delivers 90% of the functionality leveraged by the framework in the first place. Avoiding use of it, just so you can proudly declare, “it’s all OOP!”, is just denial - the majority of PHP is not OOP.