SlideShare ist ein Scribd-Unternehmen logo
1 von 65
MASTERING NAMESPACES! Nick Belhomme Spetember 17, 2011 – PFCongres The Netherlands
Software Architect / Project Lead Author of the  Zend Framework 2.0 Cookbook International Conference Speaker Contributor to various Open Source Projects Freelance PHP Consultant
www.nickbelhomme.com @NickBelhomme facebook.com/NickBelhommeFanPage Freenode irc: NickBelhomme
 
Other big programming languages support them Introduced in PHP 5.3 – Two 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. Namespace   Zendontrollerction Namespace  Zendiew Namespace  Nbe HelperLoader HelperBroker HelperPriorityStack E_ERROR explode HelperLoader HelperBroker PhpRenderer Namespace ArrayObject explode E_ERROR ArrayObject
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. Namespace  Zendontrollerction Namespace  Zendiew Namespace  Nbe HelperLoader HelperBroker HelperPriorityStack E_ERROR explode HelperLoader HelperBroker PhpRenderer Namespace ArrayObject explode E_ERROR ArrayObject
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. Namespace  Zendontrollerction Namespace  Zendiew Namespace  Nbe HelperLoader HelperBroker HelperPriorityStack E_ERROR explode HelperLoader HelperBroker PhpRenderer Namespace ArrayObject explode E_ERROR ArrayObject
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. Namespace  Zendontrollerction Namespace  Zendiew Namespace  Nbe HelperLoader HelperBroker HelperPriorityStack E_ERROR explode HelperLoader HelperBroker PhpRenderer Namespace ArrayObject explode E_ERROR ArrayObject
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. Namespace  Zendontrollerction Namespace  Zendiew Namespace  Nbe HelperLoader HelperBroker HelperPriorityStack E_ERROR explode HelperLoader HelperBroker PhpRenderer Namespace ArrayObject explode E_ERROR ArrayObject
Namespace Separator
 
PEAR Naming Convention  R.I.P. No more clever workaround for lack of namespace support No more very long function and class names R.I.P. Poor man's namespacing
 
new Zend_Layout_Controller_Action_Helper_Layout() class NbeZf_Model_User extends Nbe_Model_Abstract
new Zend_Layout_Controller_Action_Helper_Layout() new Layout() class NbeZf_Model_User extends Nbe_Model_Abstract class User extends AbstractModel
100% PURE NAMESPACES No supplements – Pure Power
The container space is created per file at the absolute top <?php namespace Nbeollection; <?php declare(encoding='UTF-8'); namespace Nbeollection; <?php /** * @namespace */ namespace Nbeollection;
The container space is created per file at the absolute top <?php namespace Nbeollection; <?php declare(encoding='UTF-8'); namespace Nbeollection; <?php /** * @namespace */ namespace Nbeollection;
The container space is created per file at the absolute top <?php namespace Nbeollection; <?php declare(encoding='UTF-8'); namespace Nbeollection; <?php /** * @namespace */ namespace Nbeollection;
Mixing Container Spaces per file <?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() { /* ... */  } <?php namespace Nbeodel { const LIBRARY_PATH = '/www/libs/Nbe'; class AbstractModel { /* ... */ } function draw() { /* ... */  } } namespace { const APP_PATH = '/www/libs/NbeZf'; function __autoload() { /* ... */  } }
Mixing Container Spaces per file <?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() { /* ... */  } <?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 NbeodelbstractModel 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 str_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: NbeModel <?php namespace Nbe; function model() { return __FUNCTION__; } echo model(); Output: Nbeodel
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  ArrayObject(); Indicate global namespace with a single backslash <----
Function fallbacks happen at Runtime <?php namespace Nbe; var_dump(explode(';', ' some;cool;words '));
Warning system functions within namespaces – Procedural Code <?php namespace WackyCode; ar_dump( explode(';', 'some;cool;words')); Don't override system functions Or explicitly call global space FULLY QUALIFIED NAMES Compile time <---- <?php namespace WackyCode; function explode($separator, $string) { // do some freaky stuff }
(Procedural) Constants fallbacks <?php namespace Nbe { echo E_ERROR; }
(Procedural) Constants fallbacks <?php namespace Nbe { E_ERROR = 10; } <?php namespace Nbe { echo E_ERROR; } <?php namespace Nbe { echo _ERROR; } Do not override system constants or Explicitly call global space Fully quaylified names, compile time
 
Fully Qualified Name Compile Time Qualified || Unqualified Name Runtime
Classses have no fallback to global scope Functions when not found in namespace fall back on global scope Constants when not found in namespace fall back on  global scope
 
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 // utils.php <?php function sayHello() { echo 'hello'; } <?php namespace Nbe; require '/utils.php'; ayHello();
Mixing Namespaces Fully Qualified namespace calling is still tedious.  So how do we solve this?
Importing to the rescue! Keyword is  use
Importing to the rescue! <?php namespace  DancingQueenntity ; use  NbeZfntitybstractEntity ; use ZendalidatortaticValidator ; class  User  extends  AbstractEntity { public function setId($id) { If (! StaticValidator ::execute($id, 'digits')) { throw new  InvalidArgumentException ('User id needs to be numeric'); } ... } }
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 ZendalidatorStaticValidator ; 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 only supported for classes
Aliasing is in-explicitly used <?php namespace DancingQueenntity; use NbeZfntityAbstractEntity  as  AbstractEntity , ZendalidatorStaticValidator  as  StaticValidator ; class User extends  AbstractEntity { public function setId($id) { If (! StaticValidator ::execute($id, 'digits')) { throw new InvalidArgumentException('User id needs to be numeric'); } ... } } Aliasing is done at compile time
Aliasing for semantics <?php namespace Nbe; use Nbeserollection as  Users ; class Group { public function setUsers( Users  $users) { $this->users = $users; } } Great for typehinting Focusing on the WHAT IS – instead on language type
Aliasing for semantics <?php namespace Nbe; use Nbeserollection as  Users ; class Group { public function setUsers($users) { if ($users instanceof  Users ) { $this->users = $users; } } } Great for typehinting Focusing on the WHAT IS – instead on language type
Dynamic Loading
Always at runtime … <?php namespace Nbe; $class = 'ArrayObject'; $object = new $class(); echo get_class($object); Output: ArrayObject … Implies absolute path or Fully Qualified Names
Always use fully qualified names for dynamic class names if they are used! <?php namespace Nbe; class Group { public function setUsers($users) { $class = 'Nbeserollection'; if ($users instanceof  $class ) { $this->users = $users; } } } Even if you are in the current namespace
From other namespace <?php namespace Nbe; $class = 'endiewhpRenderer'; $object = new $class(); echo get_class($object); Ouput: ZendiewhpRenderer
Dynamic Loading from current <?php namespace Nbe; $class = __NAMESPACE__ . '' .  'ArrayObject' ; $object = new $class(); echo get_class($object); Output: NberrayObject User Magic Constant  __NAMESPACE__
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  <?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.
Importing and Aliasing Impacts They don't cost you anything, they are a kind of memory mapping for the PHP interpreter The classes imported aren't effectively loaded into memory unless the class itself is used Added bonus when importing all the classes used at the top of the file is you get A quick dependency overview. There are static tools being developed which will read those dependencies
Explicitly Loading from current <?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(); } with  namespace  keyword <?php namespace  Nbe ; class  Exception  extends  xception {} ?>
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 a quick recap on WHY Readability Dependencies can be indicated easily System functions and constants can be overwritten It is the future, evolve with the language or loose it The market will soon require the namespace skill
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 Evans 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
Photo Credits Photos rights reserved by Sweetie187 , webtreats, royblumenthal, Brad montgomery, ktylerconk, vegetarians-dominate-meat-eaters-01, endless lazlo, DebilzBG, J. Star, quadrant6ix, notemily taken from Flickr.com

Weitere ähnliche Inhalte

Kürzlich hochgeladen

(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
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
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
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
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
 
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
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
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
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: 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
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
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
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
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
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 

Kürzlich hochgeladen (20)

(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...
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
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
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
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
 
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
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.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
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: 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
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
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...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
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.
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 

Empfohlen

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Empfohlen (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Mastering PHP Namespaces PFCongres11

  • 1. MASTERING NAMESPACES! Nick Belhomme Spetember 17, 2011 – PFCongres The Netherlands
  • 2. Software Architect / Project Lead Author of the Zend Framework 2.0 Cookbook International Conference Speaker Contributor to various Open Source Projects Freelance PHP Consultant
  • 4.  
  • 5. Other big programming languages support them Introduced in PHP 5.3 – Two 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. 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. Namespace Zendontrollerction Namespace Zendiew Namespace Nbe HelperLoader HelperBroker HelperPriorityStack E_ERROR explode HelperLoader HelperBroker PhpRenderer Namespace ArrayObject explode E_ERROR ArrayObject
  • 8. 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. Namespace Zendontrollerction Namespace Zendiew Namespace Nbe HelperLoader HelperBroker HelperPriorityStack E_ERROR explode HelperLoader HelperBroker PhpRenderer Namespace ArrayObject explode E_ERROR ArrayObject
  • 9. 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. Namespace Zendontrollerction Namespace Zendiew Namespace Nbe HelperLoader HelperBroker HelperPriorityStack E_ERROR explode HelperLoader HelperBroker PhpRenderer Namespace ArrayObject explode E_ERROR ArrayObject
  • 10. 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. Namespace Zendontrollerction Namespace Zendiew Namespace Nbe HelperLoader HelperBroker HelperPriorityStack E_ERROR explode HelperLoader HelperBroker PhpRenderer Namespace ArrayObject explode E_ERROR ArrayObject
  • 11. 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. Namespace Zendontrollerction Namespace Zendiew Namespace Nbe HelperLoader HelperBroker HelperPriorityStack E_ERROR explode HelperLoader HelperBroker PhpRenderer Namespace ArrayObject explode E_ERROR ArrayObject
  • 13.  
  • 14. PEAR Naming Convention R.I.P. No more clever workaround for lack of namespace support No more very long function and class names R.I.P. Poor man's namespacing
  • 15.  
  • 16. new Zend_Layout_Controller_Action_Helper_Layout() class NbeZf_Model_User extends Nbe_Model_Abstract
  • 17. new Zend_Layout_Controller_Action_Helper_Layout() new Layout() class NbeZf_Model_User extends Nbe_Model_Abstract class User extends AbstractModel
  • 18. 100% PURE NAMESPACES No supplements – Pure Power
  • 19. The container space is created per file at the absolute top <?php namespace Nbeollection; <?php declare(encoding='UTF-8'); namespace Nbeollection; <?php /** * @namespace */ namespace Nbeollection;
  • 20. The container space is created per file at the absolute top <?php namespace Nbeollection; <?php declare(encoding='UTF-8'); namespace Nbeollection; <?php /** * @namespace */ namespace Nbeollection;
  • 21. The container space is created per file at the absolute top <?php namespace Nbeollection; <?php declare(encoding='UTF-8'); namespace Nbeollection; <?php /** * @namespace */ namespace Nbeollection;
  • 22. Mixing Container Spaces per file <?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() { /* ... */ } <?php namespace Nbeodel { const LIBRARY_PATH = '/www/libs/Nbe'; class AbstractModel { /* ... */ } function draw() { /* ... */ } } namespace { const APP_PATH = '/www/libs/NbeZf'; function __autoload() { /* ... */ } }
  • 23. Mixing Container Spaces per file <?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() { /* ... */ } <?php namespace Nbeodel { const LIBRARY_PATH = '/www/libs/Nbe'; class AbstractModel { /* ... */ } function draw() { /* ... */ } } namespace { const APP_PATH = '/www/libs/NbeZf'; function __autoload() { /* ... */ } }
  • 24. 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
  • 25. Different name types Fully Qualified Name NbeodelbstractModel Qualified Name ModelbstractModel Unqualified Name AbstractModel
  • 26. Autoloading namespaces function __autoload($class) { require_once str_replace( '', DIRECTORY_SEPARATOR, $class ) . '.php'; } new beZfodelser() maps to NbeZfodelser require_once NbeZf/Model/User.php
  • 27. Autoloading namespaces <?php namespace Nbeoader; function autoLoader($className) { require_once str_replace('', IRECTORY_SEPARATOR, $className) . '.php'; } <?php require 'Nbe/Loader/autoloader.php'; spl_autoload_register('NbeLoaderautoloader'); $user = new Nbentityser();
  • 28. Resolving namespace calls <?php namespace Nbe; class Model {} $model = new Model(); echo get_class($model); Output: NbeModel <?php namespace Nbe; function model() { return __FUNCTION__; } echo model(); Output: Nbeodel
  • 29. 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
  • 30. Consequences <?php namespace Nbe; $collection = new ArrayObject(); Fatal error: Class 'NberrayObject' not found <?php namespace Nbe; $collection = new ArrayObject(); Indicate global namespace with a single backslash <----
  • 31. Function fallbacks happen at Runtime <?php namespace Nbe; var_dump(explode(';', ' some;cool;words '));
  • 32. Warning system functions within namespaces – Procedural Code <?php namespace WackyCode; ar_dump( explode(';', 'some;cool;words')); Don't override system functions Or explicitly call global space FULLY QUALIFIED NAMES Compile time <---- <?php namespace WackyCode; function explode($separator, $string) { // do some freaky stuff }
  • 33. (Procedural) Constants fallbacks <?php namespace Nbe { echo E_ERROR; }
  • 34. (Procedural) Constants fallbacks <?php namespace Nbe { E_ERROR = 10; } <?php namespace Nbe { echo E_ERROR; } <?php namespace Nbe { echo _ERROR; } Do not override system constants or Explicitly call global space Fully quaylified names, compile time
  • 35.  
  • 36. Fully Qualified Name Compile Time Qualified || Unqualified Name Runtime
  • 37. Classses have no fallback to global scope Functions when not found in namespace fall back on global scope Constants when not found in namespace fall back on global scope
  • 38.  
  • 39. 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
  • 40. Namespaces are per file // utils.php <?php function sayHello() { echo 'hello'; } <?php namespace Nbe; require '/utils.php'; ayHello();
  • 41. Mixing Namespaces Fully Qualified namespace calling is still tedious. So how do we solve this?
  • 42. Importing to the rescue! Keyword is use
  • 43. Importing to the rescue! <?php namespace DancingQueenntity ; use NbeZfntitybstractEntity ; use ZendalidatortaticValidator ; class User extends AbstractEntity { public function setId($id) { If (! StaticValidator ::execute($id, 'digits')) { throw new InvalidArgumentException ('User id needs to be numeric'); } ... } }
  • 44. 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'); } ... } }
  • 45. OOOH Noes a naming collision :((( <?php namespace NbeZfalidator; use ZendalidatorStaticValidator ; 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
  • 46. 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 only supported for classes
  • 47. Aliasing is in-explicitly used <?php namespace DancingQueenntity; use NbeZfntityAbstractEntity as AbstractEntity , ZendalidatorStaticValidator as StaticValidator ; class User extends AbstractEntity { public function setId($id) { If (! StaticValidator ::execute($id, 'digits')) { throw new InvalidArgumentException('User id needs to be numeric'); } ... } } Aliasing is done at compile time
  • 48. Aliasing for semantics <?php namespace Nbe; use Nbeserollection as Users ; class Group { public function setUsers( Users $users) { $this->users = $users; } } Great for typehinting Focusing on the WHAT IS – instead on language type
  • 49. Aliasing for semantics <?php namespace Nbe; use Nbeserollection as Users ; class Group { public function setUsers($users) { if ($users instanceof Users ) { $this->users = $users; } } } Great for typehinting Focusing on the WHAT IS – instead on language type
  • 51. Always at runtime … <?php namespace Nbe; $class = 'ArrayObject'; $object = new $class(); echo get_class($object); Output: ArrayObject … Implies absolute path or Fully Qualified Names
  • 52. Always use fully qualified names for dynamic class names if they are used! <?php namespace Nbe; class Group { public function setUsers($users) { $class = 'Nbeserollection'; if ($users instanceof $class ) { $this->users = $users; } } } Even if you are in the current namespace
  • 53. From other namespace <?php namespace Nbe; $class = 'endiewhpRenderer'; $object = new $class(); echo get_class($object); Ouput: ZendiewhpRenderer
  • 54. Dynamic Loading from current <?php namespace Nbe; $class = __NAMESPACE__ . '' . 'ArrayObject' ; $object = new $class(); echo get_class($object); Output: NberrayObject User Magic Constant __NAMESPACE__
  • 55. Resolution Rules <?php namespace Nbe; use Tatabe; $object = new ArrayObject(); <?php namespace Nbe; use Tatabe; $object = new NberrayObject(); Resolves to NberrayObject Resolves to TataberrayObject
  • 56. Resolution Rules <?php namespace Nbe; use Tatabe; $object = new ArrayObject(); <?php namespace Nbe; use Tatabe; $object = new NberrayObject(); Resolves to NberrayObject Resolves to TataberrayObject
  • 57. 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.
  • 58. Importing and Aliasing Impacts They don't cost you anything, they are a kind of memory mapping for the PHP interpreter The classes imported aren't effectively loaded into memory unless the class itself is used Added bonus when importing all the classes used at the top of the file is you get A quick dependency overview. There are static tools being developed which will read those dependencies
  • 59. Explicitly Loading from current <?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(); } with namespace keyword <?php namespace Nbe ; class Exception extends xception {} ?>
  • 60. 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.
  • 61. And a quick recap on WHY Readability Dependencies can be indicated easily System functions and constants can be overwritten It is the future, evolve with the language or loose it The market will soon require the namespace skill
  • 62. 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 Evans 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
  • 63. And we reached the end, Any questions?
  • 64. The End! THANK YOU [email_address] Slideshare, Twitter, IRC: NickBelhomme http://blog.nickbelhomme.com
  • 65. Photo Credits Photos rights reserved by Sweetie187 , webtreats, royblumenthal, Brad montgomery, ktylerconk, vegetarians-dominate-meat-eaters-01, endless lazlo, DebilzBG, J. Star, quadrant6ix, notemily taken from Flickr.com

Hinweis der Redaktion

  1. WHO USES NAMESPACES