Namespaces in Yii 2.0?

I’ve changed my vote to a “yes” - I’ve recently started using namespaces in a real-world project, and my initially critical assessment of the namespace feature in PHP was unwarranted.

Namespaces are in deed useful - although they don’t meet the same requirements as namespaces in statically compiled/linked languages, that is a natural deficiency stemming from the dynamic nature of the PHP language, and not a shortcoming, as I had originally thought.

With regards to Yii, the fact of the matter is that, like many other frameworks, Yii currently "emulates" namespaces, which is not longer necessary (or good) since PHP now has native syntax and support for "real" namespacing.

Moving away from the "emulated" namespaces and making use of native namespacing in PHP gets my two thumbs up!

We live and we learn… :slight_smile:

+1

Arguments like "I came form C++/.Net/Python" are cheap cause PHP is different by ideology.

We got all native functions and classes in the global namespace, as well as 99.9% code.

The classes are the namespaces in PHP.

The main reason to use namespaces is to avoide conflicts when integrating two or more ready-made applications.

If you use namespaces a lot, you end up copy-pasting a long line like

use somenamespace\class, somenamespace\class2,somenamespace\class3,\Date,\ArrayObject,\ArrayAccess

in every file of your application.

You will get happy debugging with behaviours attached from different namespaced objects, and with lambda callbacks.

NS are neither good nor bad. They are just not a language primitive you find in C/Java/.Net/Python

Since it’s new to the PHP world, I can understand the resistance…

It’s not resistance, it’s real life.

NS are not related to includes, no packages or other resorces involved, no wildcard name imports like use namespace\*

It is all about class and function name conflicts, nothing else.

Did you try to develop a serious php project intensively using namespaces? I did.

All of my serious C++ projects do.

It really surprises me to hear that ‘using namespace’ is not supported in current PHP. Is that so? :)

I’d think a simple define would do the trick then?


 use \Yii\ListView 

Will allow you be "using" namespaces in other namespaces etc etc. But there is a problem.

What we all gotta remember is that PHP’s namespaces dont work like .net’s. PHP’s implementation of them is very primative.

Let me give you an example. You have a namespace, Yii. Within that namespace you have a sub namespace named ListView.

Now to get a function or class within that namepsace you can’t autoload the namespace so you have to eager load it into the framework.

For example:

\Array\Iterate

spl_autoload_register will not see the namespace Array only the class (yes CLASS not function) Iterate. It will not autoload functions as well. The whole point of namespaces is to put functions and classes outside of global scope, but if you cannot maintain lazy loaded classes without much more work what is the point?

This is a problem! Imagine having to load all your files due to namespaces, suddenly you no longer have a glue framework. Yii, to me, is the framework since it is fast, loading the entire framework every single page will suddenly make it slow.

If PHP allowed lazy loading of namespaces then I would say go namespaces. But because they don’t namespaces should stay to the app and not its framework. Its framework is too global to be segmented by namespaces.

This makes namespaces useless in the framework itself for me, and it is one of the main reasons why I disagree with Lithium.

  1. How do you see this technically?

First problem is rules for the names-files mapping. "NS=folder" rule is simple and reliable, but not convenient for complex structures similar to Java/.Net

Next one: php scripts have the memory cleanup after each call and can’t remember the folder structure.

Ok, suppose we have some packages and a static map in a config file describing a complex NS hierarchy matching to plain files.

  1. Yii supports lazy loading through its import() method for classes.

Maybe we just need custom autoload rules support - like user-defined class, function and NS map per files?

Well uisng all those methods would add extra work ontop of using the current system.

Yes that is the way to solve NS loading problems but the first hurdle to lazy loading namespaces is to get the spl_autoload_register to see a namespace when your trying to load it otherwise you have to call it specifically.

I suppose this could be solved through the current widget handling and module handling but I am sure there are parts of the framework that would be tiresome to do via predefined functional autoloaders.

I just see using a predefined Yii autoloader for everything instead of using the default PHP handler which then Yii autoloader attaches to (via spl_autoload_register()) could make a lot of work on the app end even if your not using namespaces in your app.

Namespaces are really good for extending and overriding classes with non-native classes. It can be done with include/require but it’s not as clean as with namespaces.

i think prefix is enough :rolleyes:

One good example of namespace that I can think of is:


namespace \Yii\plugins\3rdParty\Janes {

  class DoFlip { }

}

namespace \Yii\plugins\3rdParty\Johns {

  class DoFlip { }

}


use \Yii\plugins\3rdParty\Janes\DoFlip as JaneForwardFlips

use \Yii\plugins\3rdParty\Johns\DoFlip as JohnBackFlips




$janeDoFlips = new JaneForwardFlips();

$johnDoFlips = new JohnBackFlips();



Thus, 3rd party plugin developers are able to name the class and not have to worry conflicting class definition.

autoloader (used in my PureMVC’s PHP port) to load namespaced class:


function __autoload( $class )

{

  //if( stripos( $class, '\\' ) !== false )

  if( stristr( $class, '\\' ) )

  {

    $file = APP_DIR.str_replace( '\\', '/', $class ).EXT;

    if( file_exists( $file ) )

      require_once $file;

    else

      throw new \Exception( 'Class '.$class.' not found at '.$file );

  } else

  {

    $_basePaths = array(

      PMVC_BASE_DIR.'org/puremvc/php/patterns/facade/',

      PMVC_BASE_DIR.'org/puremvc/php/interfaces/',

      PMVC_BASE_DIR.'org/puremvc/php/core/',

      PMVC_BASE_DIR.'org/puremvc/php/patterns/',

      PMVC_BASE_DIR.'org/puremvc/php/patterns/command/',

      PMVC_BASE_DIR.'org/puremvc/php/patterns/mediator/',

      PMVC_BASE_DIR.'org/puremvc/php/patterns/observer/',

      PMVC_BASE_DIR.'org/puremvc/php/patterns/proxy/' );


    $classPaths = array_merge( explode( PATH_SEPARATOR, get_include_path() ), $_basePaths );

    foreach( $classPaths as $classPath )

    {

      $file = $classPath.$class.EXT;

      if( file_exists( $file ) )

      {

        require_once $file;

        return;

      }

    }

    throw new \Exception( 'Class '.$class.' not found in '.implode( PATH_SEPARATOR,

      $classPaths ) );

  }

}

Yii can work with namespaced third party libs in its current 1.1 btw.

Thanks. I got that so far from my reading of this thread and the documentation. What I meant was supporting conforming standard so the framework can expand easily with more flexibility, IMHO.

Thinking about this issue again, today, almost a year after this discussion started.

It’s almost funny to me at this point, the idea of even considering not using namespaces. Look around on github and various other frameworks, and see how widespread adaptation of namespaces has become. It’s simply considered good practice at this point.

And it has taken less than a year to get to this point. PHP 5.3 is available on most servers at this point.

On a related note, has anybody else played around with PHP 5.4 yet? I have, and it’s pretty awesome. Traits, for one, is a brilliant feature - it basically replaces CBehavior with a native language feature.

Given the quick adoption of PHP 5.3, I personally would say, if Yii 2.0 is more than a year from release (as I’m sure it is), that I would like to see Yii 2.0 built for PHP 5.4.

By the time Yii 2.0 is released, PHP 5.5 (or 6?) will probably already be out, and Yii 2.0 will start out on a feature set that is already dated.

Building something as big as a framework, probably 1-2 years of work (at least), I would strongly recommend targeting the cutting-edge version of the language - by the time you release, this stuff will be considered old news, and your codebase might already look dated at release.

Just my opinion…

EDIT: the question we really should be asking ourselves is not "should we use namespaces", but rather "what version of PHP should we target?" - and take into account your projected release date.

mindplay

I did. Traits aren’t able to replace current CBehavior cause of lack of state. They’re almost that but what we have is a bit more.

Yes, we’ve considered this and it was discussed at Yii2 forums. No real benefits using 5.4 in the end.

That’s from scratch but we have a good foundation.

is ther was made a decision or not?

is it posible to move this topic to "Design Discussions for Yii 2.0"?

Or less, depending how you look at it.

There are very good reasons (by design) why traits don’t have, don’t need, and should not have state. You already have what you need to maintain state: objects. That’s the whole idea of OOP. Introducing another kind of entity also responsible for maintaining some state is impure, and it leads to complexity.

Letting your objects maintain their own state makes much more sense. Learn to use PHP traits and think through some examples of Yii behaviors - I’m pretty sure you’ll come to see, it makes much more sense when you designed with this kind of clear-cut separation.

Really?

For one, you would have short array syntax, which would be extremely convenient, given how everything in Yii is configured using arrays. (I realize this is a purely syntactic improvement, but one of the most widely demanded improvements in the history of PHP)

For another, well, traits - which, if you understand their justification, will lead to better, cleaner design.

Once PHP 5.4 is established and widely available, having a competing custom mechanism for horizontal extensibility will lead to inconsistencies in code, as well as unnecessary learning curve.

By the time Yii 2 is ready for prime-time, I’m pretty sure PHP 5.4 will be, too; since it’s already out, it has a significant head-start over Yii 2.

JSON serialization support, upload progress monitoring and better support for closures, to name a few others.

IMHO, anyone who’s building a framework from scratch, should build for the latest version of the language. You’re building for the future, right? Not for the past - there’s enough software for that already! :slight_smile:

5.4 is not out yet, release candidates are available, but we’re a long long way from universal 5.4 support, several years imho, much further away than Yii2.0. I think the Yii team are making the right choice here, 5.4 is of course supported and you are free to use traits and short array syntax in your application code, but requiring it in the framework is just going to massively limit adoption.

or encourage adoption of PHP 5.4? :slight_smile:

I also vote for not setting to high requirements in Yii and stick to PHP 5.3. Keep in mind that some users may run projects where they don’t have full control over which PHP version is installed on the servers. Others may have several projects on a server which can’t be upgraded to PHP 5.4 easily.

A generic framework should try to be usable by as many people as possible and not use any cutting edge features if there’s no big advantage. You would only lock out some developers this way.