How do I use namespaces with Zend Framework?

2019-02-09 01:53发布

问题:

Namespaces are really useful and PHP had no support for them until the recent few releases, AFAIK.
When I'm using Zend Framework, I have to remember long names with underscores - like Zend_Form_Element_Button or Zend_Form_Decorator_HtmlTag and so on.
If I use namespaces, this might be possible, and so much easier:

namespace Zend {
  class something {
    // ...
  }
}

namespace Zend\Form {
  class something {
    // ...
  }
}

namespace Zend\Form\Element {
  class Button {
    // ...
  }
}

And to use it I do this:

use Zend\Form\Element\Button;
$btn1 = new Button();

So my question is, is it trivially possible, given the autoloader system and a lot of meta-class "black magic" that lives inside Zend Framework, to rewrite the structure of the code using namespaces, and then have more sensible class names?
The problem is not the length of the class names - Eclipse/Netbeans/Aptana handle that very well, it is the irritant that long names are.
Tends to get confusing after some time if some classes you use have similar parts in the names.
Since ZF is open source licensed, I don't think Zend would mind a namespaced version of the code, if mere renaming and some re-organization of code can achieve that.

回答1:

Not trivial, no.

Matthew Weier O'Phinney wrote a blog about some of the issues ZF will have to face if and when they refactor the code to support PHP 5.3 namespacing:

http://weierophinney.net/matthew/archives/181-Migrating-OOP-Libraries-and-Frameworks-to-PHP-5.3.html

Abstract is a reserved word in PHP. The same goes for interfaces. Consider this particularly aggregious example:

namespace Zend::View

abstract class Abstract implements Interface
{
    // ...
}   

We've got two reserved words there: Abstract and Interface.

The Zend Framework is full of classes named Abstract and Interface. They're going to have to make a large number of backward-incompatible refactoring changes to make the ZF code support namespaces.

Also since backslash is a metacharacter in strings, any code that dynamically loads classes based on classname, such as Zend_Db::factory() or Zend_Filter_Input, is unnecessarily difficult to implement, because of the hare-brained decision the PHP core team made, using backslash as the namespace separator.