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

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)James Titcumb
 
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 betterZendCon
 
DevOps in PHP environment
DevOps in PHP environment DevOps in PHP environment
DevOps in PHP environment Evaldo Felipe
 
CLI, the other SAPI
CLI, the other SAPICLI, the other SAPI
CLI, the other SAPICombell NV
 
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 PHPGuilherme Blanco
 
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)James Titcumb
 
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.4Wim Godden
 
How to deploy node to production
How to deploy node to productionHow to deploy node to production
How to deploy node to productionSean Hess
 
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 2011Wim Godden
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHPBradley Holt
 
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 (Кирилл Чебунин)ZFConf Conference
 
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 PHPGuilherme Blanco
 
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 DeckrICh morrow
 

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

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.3Jeremy Coates
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
Preparing for the next php version
Preparing for the next php versionPreparing for the next php version
Preparing for the next php versionDamien Seguy
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboardsDenis Ristic
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.pptJamers2
 
Introduction to Modern Perl
Introduction to Modern PerlIntroduction to Modern Perl
Introduction to Modern PerlDave Cross
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
PHP: The easiest language to learn.
PHP: The easiest language to learn.PHP: The easiest language to learn.
PHP: The easiest language to learn.Binny V A
 
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)Damien Seguy
 
Giới thiệu PHP 7
Giới thiệu PHP 7Giới thiệu PHP 7
Giới thiệu PHP 7ZendVN
 
New Stuff In Php 5.3
New Stuff In Php 5.3New Stuff In Php 5.3
New Stuff In Php 5.3Chris Chubb
 
Php 7 compliance workshop singapore
Php 7 compliance workshop singaporePhp 7 compliance workshop singapore
Php 7 compliance workshop singaporeDamien Seguy
 

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 AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
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

Vagrant move over, here is Docker
Vagrant move over, here is DockerVagrant move over, here is Docker
Vagrant move over, here is DockerNick Belhomme
 
Mastering selenium for automated acceptance tests
Mastering selenium for automated acceptance testsMastering selenium for automated acceptance tests
Mastering selenium for automated acceptance testsNick Belhomme
 
PHP Quality Assurance Workshop PHPBenelux
PHP Quality Assurance Workshop PHPBeneluxPHP Quality Assurance Workshop PHPBenelux
PHP Quality Assurance Workshop PHPBeneluxNick Belhomme
 
Zend Framework Form: Mastering Decorators
Zend Framework Form: Mastering DecoratorsZend Framework Form: Mastering Decorators
Zend Framework Form: Mastering DecoratorsNick Belhomme
 
Zend Framework 1.8 workshop
Zend Framework 1.8 workshopZend Framework 1.8 workshop
Zend Framework 1.8 workshopNick Belhomme
 

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

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 

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