SlideShare a Scribd company logo
1 of 36
MASTERING NAMESPACES! Nick Belhomme January 29, 2011 – PHPBenelux Conference
About Me @NickBelhomme Freelance PHP Consultant  International Conference Speaker  Zend Framework 2.0 Cookbook Author  Contributor to various Open Source Projects  ZCE  ZFCE
Passions Life Traveling People Sharing Ideas Networking
Dreams A world of unbounded potential. Where everybody believes they can Be, do and have whatever they think about. Think your idea Act upon your idea Refine later
BACK TO NAMESPACES <----
Why Other big programming languages support them Introduced in PHP 5.3 – One and a half years ago Modern Next Gen Frameworks (Symfony 2.0, Zend Framework 2.0 and others) Job market demands it Use it or loose it
What are they? Abstract container created to hold a logical grouping of unique identifiers. Unique identifiers are names. (in practice: classes, functions, constants) Each identifier is associated with the namespace where it is defined.
PEAR Naming Convention  R.I.P. No more clever workaround for lack of namespace support No more very long function and class names
Welcome Readability new Zend_Layout_Controller_Action_Helper_Layout() new Layout() class NbeZf_Model_User extends Nbe_Model_Abstract class User extends AbstractModel
How to create the container space <?php namespace Nbeollection; <?php declare(encoding='UTF-8'); namespace Nbeollection; Per file <?php /** * @namespace */ namespace Nbeollection;
How to create the container space <?php namespace Nbeodel; const LIBRARY_PATH = '/www/libs/Nbe'; class AbstractModel { /* ... */ } function draw() { /* ... */  } namespace NbeZf; const LIBRARY_PATH = '/www/libs/NbeZf'; class AbstractModel { /* ... */ } function sayHello() { /* ... */  } Mixing spaces per file <?php namespace Nbeodel { const LIBRARY_PATH = '/www/libs/Nbe'; class AbstractModel { /* ... */ } function draw() { /* ... */  } } namespace { const APP_PATH = '/www/libs/NbeZf'; function __autoload() { /* ... */  } }
Common Mistakes <?php namespace be; // rest of code Fatal error: Undefined constant 'Nbe' <?php namespace Nbe; class Interface {} <?php namespace Nbe; class Abstract {} Parse error: syntax error, unexpected T_INTERFACE Parse error: syntax error, unexpected T_ABSTRACT
Different name types Fully Qualified Name beodelbstractModel Qualified Name ModelbstractModel Unqualified Name AbstractModel
Autoloading namespaces function __autoload($class) { require_once str_replace( '',  DIRECTORY_SEPARATOR,  $class ) . '.php'; } new beZfodelser() maps to NbeZfodelser require_once /NbeZf/Model/User.php
Autoloading namespaces <?php namespace Nbeoader; function autoLoader($className) { require_once tr_replace('', IRECTORY_SEPARATOR, $className) . '.php'; } <?php require 'Nbe/Loader/autoloader.php'; spl_autoload_register('NbeLoaderautoloader'); $user = new Nbentityser();
Resolving namespace calls <?php namespace Nbe; class Model {} $model = new Model(); echo get_class($model); Output: Nbeodel <?php namespace Nbe; function model() { return __FUNCTION__; } echo model(); Output: Nbeodel
Consequences <?php namespace Nbe; $collection = new ArrayObject(); Fatal error: Class 'NberrayObject' not found <?php namespace Nbe; $collection = new rrayObject(); Indicate global namespace with a single backslash <----
Function fallbacks <?php namespace Nbe; var_dump(explode(';', ' some;cool;words ')); <?php namespace Nbe; ar_dump( explode(';', 'some;cool;words')); Better practice. Explicitly call global space FULLY QUALIFIED NAMES Compile time <---- Runtime and potential  happy debugging feature <----
Constants fallbacks <?php namespace { const APP = 'test'; } namespace Nbe { const E_ERROR = 10; echo APP; echo E_ERROR; } Better practice. Explicitly call global space Fully quaylified names, compile time <?php namespace { const APP = 'test'; } namespace Nbe { const E_ERROR = 10; echo PP; echo E_ERROR; } Runtime and potential  happy debugging feature
Magic constants beware <?php namespace Nbe; echo __LINE__; echo __FILE__; echo __DIR__; echo __FUNCTION__; echo __CLASS__; echo __METHOD__; echo __NAMESPACE__; Magic constants cannot be overwritten so no global namespace prefix is allowed
Namespaces are per file <?php function sayHello() { echo 'hello'; } <?php namespace Nbe; require '/utils.php'; ayHello();
But what about using other namespaces? Fully Qualified namespace calling is still tedious.  So how do we solve this? ?
Importing to the rescue! <?php namespace DancingQueenntity; use NbeZfntitybstractEntity, ZendalidatortaticValidator; class User extends AbstractEntity { public function setId($id) { If (!StaticValidator::execute($id, 'digits')) { throw new InvalidArgumentException('User id needs to be numeric'); } ... } }
OOOH Noes a naming collision :((( <?php namespace NbeZfalidator; use ZendalidatortaticValidator; class StaticValidator extends StaticValidator  { public static function getBroker() { if (null === self::$broker) { static::setBroker(new ValidatorBroker()); } return self::$broker; } } Fatal error: Cannot declare class  NbeZfalidatortaticValidator  because the name is already in use
Aliasing to the rescue! <?php namespace NbeZfalidator; use ZendalidatortaticValidator as ZfStaticValidator; class StaticValidator extends ZfStaticValidator  { public static function getBroker() { if (null === self::$broker) { static::setBroker(new ValidatorBroker()); } return self::$broker; } }
Aliasing is in-explicitly used <?php namespace DancingQueenntity; use NbeZfntitybstractEntity as AbstractEntity, ZendalidatortaticValidator as StaticValidator; class User extends AbstractEntity { public function setId($id) { If (!StaticValidator::execute($id, 'digits')) { throw new InvalidArgumentException('User id needs to be numeric'); } ... } }
Dynamic Loading <?php namespace Nbe; $class = 'ArrayObject'; $object = new $class(); echo get_class($object); Output: ArrayObject Always Absolute Path
Dynamic Loading from other namespace <?php namespace Nbe; $class = 'endiewhpRenderer'; $object = new $class(); echo get_class($object); Ouput: ZendiewhpRenderer Fully qualified names
Dynamic Loading from current <?php namespace Nbe; $class = __NAMESPACE__ . '' .  'ArrayObject'; $object = new $class(); echo get_class($object); Output: NberrayObject
Resolution Rules  <?php namespace Nbe; use Tatabe; $object = new ArrayObject(); <?php namespace Nbe; use Tatabe; $object = new NberrayObject(); Resolves to NberrayObject Resolves to TataberrayObject
Resolution Rules for Dummies When an alias is available – and there is always an alias available when importing - all unqualified and qualified names are translated using the current import rules. When no alias is available all unqualified and qualified names have the current namespace prepended. Constants and functions have fallbacks to global namespace for unqualified names.
Explicitly Loading from current <?php namespace Nbe; class Exception extends xception{} ?> <?php namespace Nbe; use Exception; const ERROR_INFO = 10; try { try { if (1===1) { throw new Exception('instantiates xception'); } } catch (xception $e) { throw new namespacexception('instantiates bexception', ERROR_INFO, $e); } } catch (namespacexception $e) { echo 'error: '.$e->getMessage(); echo PHP_EOL; echo 'nested exception error: '.$e->getPrevious()->getMessage(); } File 1 File 2 namespace keyword
Coming to an end, but first some Timeline changes PHP4 class constructor has the same name as the class > PHP5 class constructor is  __construct but accepts PHP4 convention >5.3 namespaces are introduced, nothing changes >= 5.3.3 Backward compatibility change. Only __construct is now regarded as the constructor for namespaced code.
And some cool resources The PHP manual  http://www.php.net/namespaces Ralph Schindlers namespace convert tool https://github.com/ralphschindler/PHPTools Plus comments on it by Cal Evan http://blog.calevans.com/2010/03/27/zends-new-namespace-converter/ Google: php namespaces http://www.google.be/search?q=php+namespaces Zend Framework 2.0 Cookbook http://blog.nickbelhomme.com/php/zend-framework-2-0-cookbook_324
And we reached the end, Any questions?
The End! THANK YOU [email_address] Slideshare, Twitter, IRC: NickBelhomme http://blog.nickbelhomme.com

More Related Content

What's hot

How to deploy node to production
How to deploy node to productionHow to deploy node to production
How to deploy node to production
Sean Hess
 

What's hot (20)

Diving into HHVM Extensions (PHPNW Conference 2015)
Diving into HHVM Extensions (PHPNW Conference 2015)Diving into HHVM Extensions (PHPNW Conference 2015)
Diving into HHVM Extensions (PHPNW Conference 2015)
 
Get your teeth into Plack
Get your teeth into PlackGet your teeth into Plack
Get your teeth into Plack
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
DevOps in PHP environment
DevOps in PHP environment DevOps in PHP environment
DevOps in PHP environment
 
CLI, the other SAPI
CLI, the other SAPICLI, the other SAPI
CLI, the other SAPI
 
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHPIPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
 
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
 
Modern PHP
Modern PHPModern PHP
Modern PHP
 
PHP7 is coming
PHP7 is comingPHP7 is coming
PHP7 is coming
 
Spl in the wild
Spl in the wildSpl in the wild
Spl in the wild
 
The why and how of moving to php 5.4
The why and how of moving to php 5.4The why and how of moving to php 5.4
The why and how of moving to php 5.4
 
How to deploy node to production
How to deploy node to productionHow to deploy node to production
How to deploy node to production
 
Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
PHP
PHPPHP
PHP
 
ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)
ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)
ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)
 
Api Design
Api DesignApi Design
Api Design
 
Doctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHPDoctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHP
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 

Similar to Mastering Namespaces in PHP

PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
jsmith92
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 

Similar to Mastering Namespaces in PHP (20)

What's new, what's hot in PHP 5.3
What's new, what's hot in PHP 5.3What's new, what's hot in PHP 5.3
What's new, what's hot in PHP 5.3
 
PHP 5.3
PHP 5.3PHP 5.3
PHP 5.3
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Preparing for the next php version
Preparing for the next php versionPreparing for the next php version
Preparing for the next php version
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
 
Introduction to Modern Perl
Introduction to Modern PerlIntroduction to Modern Perl
Introduction to Modern Perl
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Using PHP 5.3 Namespaces for Fame and Fortune
Using PHP 5.3 Namespaces for Fame and FortuneUsing PHP 5.3 Namespaces for Fame and Fortune
Using PHP 5.3 Namespaces for Fame and Fortune
 
Modern php
Modern phpModern php
Modern php
 
PHP: The easiest language to learn.
PHP: The easiest language to learn.PHP: The easiest language to learn.
PHP: The easiest language to learn.
 
Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Giới thiệu PHP 7
Giới thiệu PHP 7Giới thiệu PHP 7
Giới thiệu PHP 7
 
New Stuff In Php 5.3
New Stuff In Php 5.3New Stuff In Php 5.3
New Stuff In Php 5.3
 
Php 7 compliance workshop singapore
Php 7 compliance workshop singaporePhp 7 compliance workshop singapore
Php 7 compliance workshop singapore
 

More from Nick Belhomme (6)

Vagrant move over, here is Docker
Vagrant move over, here is DockerVagrant move over, here is Docker
Vagrant move over, here is Docker
 
Mastering selenium for automated acceptance tests
Mastering selenium for automated acceptance testsMastering selenium for automated acceptance tests
Mastering selenium for automated acceptance tests
 
PHP Quality Assurance Workshop PHPBenelux
PHP Quality Assurance Workshop PHPBeneluxPHP Quality Assurance Workshop PHPBenelux
PHP Quality Assurance Workshop PHPBenelux
 
Cursus phpunit
Cursus phpunitCursus phpunit
Cursus phpunit
 
Zend Framework Form: Mastering Decorators
Zend Framework Form: Mastering DecoratorsZend Framework Form: Mastering Decorators
Zend Framework Form: Mastering Decorators
 
Zend Framework 1.8 workshop
Zend Framework 1.8 workshopZend Framework 1.8 workshop
Zend Framework 1.8 workshop
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Mastering Namespaces in PHP

  • 1. MASTERING NAMESPACES! Nick Belhomme January 29, 2011 – PHPBenelux Conference
  • 2. About Me @NickBelhomme Freelance PHP Consultant International Conference Speaker Zend Framework 2.0 Cookbook Author Contributor to various Open Source Projects ZCE ZFCE
  • 3. Passions Life Traveling People Sharing Ideas Networking
  • 4. Dreams A world of unbounded potential. Where everybody believes they can Be, do and have whatever they think about. Think your idea Act upon your idea Refine later
  • 6. Why Other big programming languages support them Introduced in PHP 5.3 – One and a half years ago Modern Next Gen Frameworks (Symfony 2.0, Zend Framework 2.0 and others) Job market demands it Use it or loose it
  • 7. What are they? Abstract container created to hold a logical grouping of unique identifiers. Unique identifiers are names. (in practice: classes, functions, constants) Each identifier is associated with the namespace where it is defined.
  • 8. PEAR Naming Convention R.I.P. No more clever workaround for lack of namespace support No more very long function and class names
  • 9. Welcome Readability new Zend_Layout_Controller_Action_Helper_Layout() new Layout() class NbeZf_Model_User extends Nbe_Model_Abstract class User extends AbstractModel
  • 10. How to create the container space <?php namespace Nbeollection; <?php declare(encoding='UTF-8'); namespace Nbeollection; Per file <?php /** * @namespace */ namespace Nbeollection;
  • 11. How to create the container space <?php namespace Nbeodel; const LIBRARY_PATH = '/www/libs/Nbe'; class AbstractModel { /* ... */ } function draw() { /* ... */ } namespace NbeZf; const LIBRARY_PATH = '/www/libs/NbeZf'; class AbstractModel { /* ... */ } function sayHello() { /* ... */ } Mixing spaces per file <?php namespace Nbeodel { const LIBRARY_PATH = '/www/libs/Nbe'; class AbstractModel { /* ... */ } function draw() { /* ... */ } } namespace { const APP_PATH = '/www/libs/NbeZf'; function __autoload() { /* ... */ } }
  • 12. Common Mistakes <?php namespace be; // rest of code Fatal error: Undefined constant 'Nbe' <?php namespace Nbe; class Interface {} <?php namespace Nbe; class Abstract {} Parse error: syntax error, unexpected T_INTERFACE Parse error: syntax error, unexpected T_ABSTRACT
  • 13. Different name types Fully Qualified Name beodelbstractModel Qualified Name ModelbstractModel Unqualified Name AbstractModel
  • 14. Autoloading namespaces function __autoload($class) { require_once str_replace( '', DIRECTORY_SEPARATOR, $class ) . '.php'; } new beZfodelser() maps to NbeZfodelser require_once /NbeZf/Model/User.php
  • 15. Autoloading namespaces <?php namespace Nbeoader; function autoLoader($className) { require_once tr_replace('', IRECTORY_SEPARATOR, $className) . '.php'; } <?php require 'Nbe/Loader/autoloader.php'; spl_autoload_register('NbeLoaderautoloader'); $user = new Nbentityser();
  • 16. Resolving namespace calls <?php namespace Nbe; class Model {} $model = new Model(); echo get_class($model); Output: Nbeodel <?php namespace Nbe; function model() { return __FUNCTION__; } echo model(); Output: Nbeodel
  • 17. Consequences <?php namespace Nbe; $collection = new ArrayObject(); Fatal error: Class 'NberrayObject' not found <?php namespace Nbe; $collection = new rrayObject(); Indicate global namespace with a single backslash <----
  • 18. Function fallbacks <?php namespace Nbe; var_dump(explode(';', ' some;cool;words ')); <?php namespace Nbe; ar_dump( explode(';', 'some;cool;words')); Better practice. Explicitly call global space FULLY QUALIFIED NAMES Compile time <---- Runtime and potential happy debugging feature <----
  • 19. Constants fallbacks <?php namespace { const APP = 'test'; } namespace Nbe { const E_ERROR = 10; echo APP; echo E_ERROR; } Better practice. Explicitly call global space Fully quaylified names, compile time <?php namespace { const APP = 'test'; } namespace Nbe { const E_ERROR = 10; echo PP; echo E_ERROR; } Runtime and potential happy debugging feature
  • 20. Magic constants beware <?php namespace Nbe; echo __LINE__; echo __FILE__; echo __DIR__; echo __FUNCTION__; echo __CLASS__; echo __METHOD__; echo __NAMESPACE__; Magic constants cannot be overwritten so no global namespace prefix is allowed
  • 21. Namespaces are per file <?php function sayHello() { echo 'hello'; } <?php namespace Nbe; require '/utils.php'; ayHello();
  • 22. But what about using other namespaces? Fully Qualified namespace calling is still tedious. So how do we solve this? ?
  • 23. Importing to the rescue! <?php namespace DancingQueenntity; use NbeZfntitybstractEntity, ZendalidatortaticValidator; class User extends AbstractEntity { public function setId($id) { If (!StaticValidator::execute($id, 'digits')) { throw new InvalidArgumentException('User id needs to be numeric'); } ... } }
  • 24. OOOH Noes a naming collision :((( <?php namespace NbeZfalidator; use ZendalidatortaticValidator; class StaticValidator extends StaticValidator { public static function getBroker() { if (null === self::$broker) { static::setBroker(new ValidatorBroker()); } return self::$broker; } } Fatal error: Cannot declare class NbeZfalidatortaticValidator because the name is already in use
  • 25. Aliasing to the rescue! <?php namespace NbeZfalidator; use ZendalidatortaticValidator as ZfStaticValidator; class StaticValidator extends ZfStaticValidator { public static function getBroker() { if (null === self::$broker) { static::setBroker(new ValidatorBroker()); } return self::$broker; } }
  • 26. Aliasing is in-explicitly used <?php namespace DancingQueenntity; use NbeZfntitybstractEntity as AbstractEntity, ZendalidatortaticValidator as StaticValidator; class User extends AbstractEntity { public function setId($id) { If (!StaticValidator::execute($id, 'digits')) { throw new InvalidArgumentException('User id needs to be numeric'); } ... } }
  • 27. Dynamic Loading <?php namespace Nbe; $class = 'ArrayObject'; $object = new $class(); echo get_class($object); Output: ArrayObject Always Absolute Path
  • 28. Dynamic Loading from other namespace <?php namespace Nbe; $class = 'endiewhpRenderer'; $object = new $class(); echo get_class($object); Ouput: ZendiewhpRenderer Fully qualified names
  • 29. Dynamic Loading from current <?php namespace Nbe; $class = __NAMESPACE__ . '' . 'ArrayObject'; $object = new $class(); echo get_class($object); Output: NberrayObject
  • 30. Resolution Rules <?php namespace Nbe; use Tatabe; $object = new ArrayObject(); <?php namespace Nbe; use Tatabe; $object = new NberrayObject(); Resolves to NberrayObject Resolves to TataberrayObject
  • 31. Resolution Rules for Dummies When an alias is available – and there is always an alias available when importing - all unqualified and qualified names are translated using the current import rules. When no alias is available all unqualified and qualified names have the current namespace prepended. Constants and functions have fallbacks to global namespace for unqualified names.
  • 32. Explicitly Loading from current <?php namespace Nbe; class Exception extends xception{} ?> <?php namespace Nbe; use Exception; const ERROR_INFO = 10; try { try { if (1===1) { throw new Exception('instantiates xception'); } } catch (xception $e) { throw new namespacexception('instantiates bexception', ERROR_INFO, $e); } } catch (namespacexception $e) { echo 'error: '.$e->getMessage(); echo PHP_EOL; echo 'nested exception error: '.$e->getPrevious()->getMessage(); } File 1 File 2 namespace keyword
  • 33. Coming to an end, but first some Timeline changes PHP4 class constructor has the same name as the class > PHP5 class constructor is __construct but accepts PHP4 convention >5.3 namespaces are introduced, nothing changes >= 5.3.3 Backward compatibility change. Only __construct is now regarded as the constructor for namespaced code.
  • 34. And some cool resources The PHP manual http://www.php.net/namespaces Ralph Schindlers namespace convert tool https://github.com/ralphschindler/PHPTools Plus comments on it by Cal Evan http://blog.calevans.com/2010/03/27/zends-new-namespace-converter/ Google: php namespaces http://www.google.be/search?q=php+namespaces Zend Framework 2.0 Cookbook http://blog.nickbelhomme.com/php/zend-framework-2-0-cookbook_324
  • 35. And we reached the end, Any questions?
  • 36. The End! THANK YOU [email_address] Slideshare, Twitter, IRC: NickBelhomme http://blog.nickbelhomme.com