SlideShare uma empresa Scribd logo
1 de 42
Using PHP 5.3 Namespaces
for Fame and Fortune
Matthew Weier O'Phinney
Project Lead, Zend Framework




                               © All rights reserved. Zend Technologies, Inc.
What are “namespaces”?




     © All rights reserved. Zend Technologies, Inc.
What are “namespaces”?

                 "A way in which to group
 related classes, functions and constants"
                                           – http://php.net/namespace




       © All rights reserved. Zend Technologies, Inc.
Basics




© All rights reserved. Zend Technologies, Inc.
Namespace Separator




                  “”
                                                                Get over it!


               © All rights reserved. Zend Technologies, Inc.
What can live in namespaces
●   Classes
●   Constants
●   Functions




                © All rights reserved. Zend Technologies, Inc.
Declaring namespaces
●   Single line declaration
    namespace Foo;




                     © All rights reserved. Zend Technologies, Inc.
Declaring namespaces
●   Block declaration
    namespace Foo
    {
    }
    namespace Bar
    {
    }




                    © All rights reserved. Zend Technologies, Inc.
Subnamespaces
●   Separate the subnamespaces using the
    namespace separator
    namespace FooBar;

    namespace FooBarBaz;




                     © All rights reserved. Zend Technologies, Inc.
Referring to namespaced elements
●   From non-namespaced code:
    $class = new FooBarClass();
    $class = new FooBarBazClass();
    FoobarFunc(); // function call
    $val = FooBAT; // constant value




                    © All rights reserved. Zend Technologies, Inc.
Referring to namespaced elements
●   From code using the same namespace:
    namespace Foo;

    $class = new BarClass();
    $class = new BarBazClass();
    barFunc(); // function call
    $val = BAT; // constant value




                     © All rights reserved. Zend Technologies, Inc.
Referring to namespaced elements
●   From code in a different namespace:
    namespace Bar;

    $class = new FooBarClass();
    $class = new FooBarBazClass();
    FoobarFunc(); // function call
    $val = FooBAT; // constant value




                     © All rights reserved. Zend Technologies, Inc.
Using namespaced code:
●   Prefixing with a namespace separator resolves
    as a fully qualified name
●   Resolution order:
    ▶   Globally qualified: known; otherwise:
    ▶   Current namespace, or relative to it
        (Classes, functions, constants)
    ▶   Global namespace
        (functions, constants)



                         © All rights reserved. Zend Technologies, Inc.
Importing namespaces
●   A way to bring code from another namespace
    into the current namespace.
●   Import:
    ▶   Classes
    ▶   Other namespaces
●   Keyword used is use




                      © All rights reserved. Zend Technologies, Inc.
Importing namespaces

  namespace Foo;
  class Bar {}

  namespace Bar;
  use Foo;     // imports namespace
  use FooBar; // imports class




                   © All rights reserved. Zend Technologies, Inc.
Using imported code

  namespace Bar;
  use Foo;     // imports namespace
  $bar = new FooBar();

  namespace Bar;
  use FooBar; // imports class
  $bar = new Bar();




                  © All rights reserved. Zend Technologies, Inc.
Aliasing
●   "import namespace or class, but refer to it
    using this name"
●   PHP utilizes the as keyword to alias




                     © All rights reserved. Zend Technologies, Inc.
Aliasing

  namespace Bar;
  use Foo as f;
  $bar = new fBar();

  namespace Bar;
  use FooBar as bar;
  $bar = new bar();




                  © All rights reserved. Zend Technologies, Inc.
Make typehinting more semantic!

namespace App;
use ZendEventManagerEventManager as Events;

class Foo
{
    public function events(Events $events = null)
    {
        if ($events instanceof Events) {
            $this->events = $events;
        } elseif (!$this->events instanceof Events) {
            $this->events = new Events(__CLASS__);
        }
        return $this->events;
    }
}


                    © All rights reserved. Zend Technologies, Inc.
Importing multiple namespaces/classes
●   Multiple use statements
    namespace BazBat;
    use Foo;
    use Bar;




                    © All rights reserved. Zend Technologies, Inc.
Importing multiple namespaces/classes
●   Or use a comma (“,”) to separate statements
    namespace BazBat;
    use Foo,
        Bar;




                    © All rights reserved. Zend Technologies, Inc.
Importing multiple namespaces/classes
●   With aliases
    namespace BazBat;

    use Foo as f, // aliased
        Bar;      // not aliased




                        © All rights reserved. Zend Technologies, Inc.
What namespace are you in?
●   __NAMESPACE__




                © All rights reserved. Zend Technologies, Inc.
Comprehensive example
●   The setup:
    namespace FooBar;
    const BAZ = 1;
    function baz($data) {}
    class Baz {}

    namespace FooBaz;
    const BAZ = 2;
    function baz($data) {}
    class Baz {}




                    © All rights reserved. Zend Technologies, Inc.
Comprehensive example
namespace Test;
use FooBarBaz as BarBaz,
    FooBaz;

const BAZ = 3;
echo BAZ;          // 3
echo BazBAZ;      // 2
echo FooBarBAZ; // 1

$baz = new BarBaz(); // FooBarBaz
$baz = new Baz();     // E_FATAL (no matching class)
$baz = new BazBaz(); // FooBazBaz

baz($baz);     // E_FATAL (no matching function in
               // current namespace)
Bazbaz($baz); // FooBazbaz()

                    © All rights reserved. Zend Technologies, Inc.
Pitfalls




© All rights reserved. Zend Technologies, Inc.
Referencing namespaced code in strings
●   Classes, constants, and functions referenced in
    a string MUST be fully qualified
●   No namespace separator prefix is necessary




                     © All rights reserved. Zend Technologies, Inc.
Referencing namespaced code in strings
●   Example 1
    namespace Foo;
    // Assume FooBarBaz is a defined class

    $class = 'BarBaz';
    $o     = new $class; // E_FATAL; can't find
                         // relative names

    $class = 'FooBarBaz';
    $o     = new $class; // Success

    $class = 'FooBarBaz';
    $o     = new $class; // Also success,
                         // but not necessary

                    © All rights reserved. Zend Technologies, Inc.
Referencing namespaced code in strings
●   Example 2
    namespace Foo;
    // Assume FooBarBaz is a defined class

    $class = 'BarBaz';
    if ($o instanceof $class) { } // Fails; can't
                                  // resolve class

    $class = 'FooBarBaz';
    if ($o instanceof $class) { } // Success




                    © All rights reserved. Zend Technologies, Inc.
Why use namespaces?




    © All rights reserved. Zend Technologies, Inc.
Code Organization: Filesystem
●   Namespace separator has an affinity for the
    directory separator
●   Suggests a 1:1 relationship with file system
    namespace FooBar;
    class Baz {}
    /* Foo/Bar/Baz.php (*nix)
       FooBarBaz.php (Windows) */




                     © All rights reserved. Zend Technologies, Inc.
Code Organization: By Responsibility
●   Interfaces
    ▶   Use cases:
         ●   instanceof: $class instanceof Adapter
         ●   implements: SomeClass implements Adapter
    ▶   Natural language is easiest to understand
    ▶   Natural language suggests a hierarchy




                             © All rights reserved. Zend Technologies, Inc.
Code Organization: By Responsibility

    namespace ComponentAdapter;
    use ComponentAdapter;

    class ConcreteAdapter implements Adapter
    {}



●   interface ComponentAdapter in
    Component/Adapter.php
●   class ComponentAdapterConcreteAdapter in
    Component/Adapter/ConcreteAdapter.php

                     © All rights reserved. Zend Technologies, Inc.
Code Organization: By Responsibility
●   Takeaway: we're referencing the capabilities,
    not the language type




                     © All rights reserved. Zend Technologies, Inc.
Readability
●   When within a namespace, reference classes
    directly, keeping usage succinct
    namespace ZendHttp;
    $client = new Client();




                     © All rights reserved. Zend Technologies, Inc.
Readability
●   Importing and aliasing make names more
    succinct
    namespace Application;
    use ZendHttpClient as HttpClient,
        ZendLoggerLogger;

    $client = new HttpClient();
    $log    = new Logger();




                     © All rights reserved. Zend Technologies, Inc.
Readability
●   Aliasing allows giving names context
    namespace ApplicationController;

    use ZendControllerAction
        as ActionController;

    class FooController
        extends ActionController {}




                     © All rights reserved. Zend Technologies, Inc.
Dependency declarations
●   Suggestion: import every class outside the
    current namespace that you consume
    namespace ApplicationController;

    use ZendControllerAction
            as ActionController,
        MyORMMapper as DataMapper,
        MyEntityBlogEntry,
        ZendEventManagerEventManager;




                     © All rights reserved. Zend Technologies, Inc.
Dependency declarations
●   Imports are hints to the interpreter, and don't
    cost anything
●   Helps to document dependencies up front
●   Allows static analysis to determine
    dependencies




                     © All rights reserved. Zend Technologies, Inc.
Resources




© All rights reserved. Zend Technologies, Inc.
●   PHP Manual: http://php.net/namespace




                   © All rights reserved. Zend Technologies, Inc.
Webinar
To watch the recorded webinar, please go to


http://www.zend.com/en/webinar/Framework/
70170000000bWGR-PHP-Namespaces.flv
or

http://bit.ly/pcVMKR

(a short registration is required)




                                     © All rights reserved. Zend Technologies, Inc.

Mais conteúdo relacionado

Mais procurados

PHP Underground Session 1: The Basics
PHP Underground Session 1: The BasicsPHP Underground Session 1: The Basics
PHP Underground Session 1: The Basics
Robin Hawkes
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
Nick Belhomme
 
Perl 101 - The Basics of Perl Programming
Perl  101 - The Basics of Perl ProgrammingPerl  101 - The Basics of Perl Programming
Perl 101 - The Basics of Perl Programming
Utkarsh Sengar
 

Mais procurados (20)

Unit 1-introduction to perl
Unit 1-introduction to perlUnit 1-introduction to perl
Unit 1-introduction to perl
 
PHP Underground Session 1: The Basics
PHP Underground Session 1: The BasicsPHP Underground Session 1: The Basics
PHP Underground Session 1: The Basics
 
Mastering Namespaces in PHP
Mastering Namespaces in PHPMastering Namespaces in PHP
Mastering Namespaces in PHP
 
Introduction to php php++
Introduction to php php++Introduction to php php++
Introduction to php php++
 
PHP - Introduction to PHP
PHP -  Introduction to PHPPHP -  Introduction to PHP
PHP - Introduction to PHP
 
PHPBootcamp - Zend Framework
PHPBootcamp - Zend FrameworkPHPBootcamp - Zend Framework
PHPBootcamp - Zend Framework
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners Perl
 
Yapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line PerlYapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line Perl
 
PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | Edureka
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
 
PHP Basic
PHP BasicPHP Basic
PHP Basic
 
Extending Zend Framework
Extending Zend FrameworkExtending Zend Framework
Extending Zend Framework
 
PHP - Introduction to PHP Functions
PHP -  Introduction to PHP FunctionsPHP -  Introduction to PHP Functions
PHP - Introduction to PHP Functions
 
Perl 101 - The Basics of Perl Programming
Perl  101 - The Basics of Perl ProgrammingPerl  101 - The Basics of Perl Programming
Perl 101 - The Basics of Perl Programming
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
Prersentation
PrersentationPrersentation
Prersentation
 

Semelhante a Using PHP 5.3 Namespaces for Fame and Fortune

Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
maheshm1206
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 

Semelhante a Using PHP 5.3 Namespaces for Fame and Fortune (20)

Zend Framework 2 Patterns
Zend Framework 2 PatternsZend Framework 2 Patterns
Zend Framework 2 Patterns
 
ZF2 Presentation @PHP Tour 2011 in Lille
ZF2 Presentation @PHP Tour 2011 in LilleZF2 Presentation @PHP Tour 2011 in Lille
ZF2 Presentation @PHP Tour 2011 in Lille
 
Zend Framework 2 quick start
Zend Framework 2 quick startZend Framework 2 quick start
Zend Framework 2 quick start
 
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
 
A quick start on Zend Framework 2
A quick start on Zend Framework 2A quick start on Zend Framework 2
A quick start on Zend Framework 2
 
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
 
Licão 09 variables and arrays v2
Licão 09 variables and arrays v2Licão 09 variables and arrays v2
Licão 09 variables and arrays v2
 
Getting Into FLOW3 (DPC12)
Getting Into FLOW3 (DPC12)Getting Into FLOW3 (DPC12)
Getting Into FLOW3 (DPC12)
 
New Stuff In Php 5.3
New Stuff In Php 5.3New Stuff In Php 5.3
New Stuff In Php 5.3
 
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
 
PHP Introduction and Training Material
PHP Introduction and Training MaterialPHP Introduction and Training Material
PHP Introduction and Training Material
 
IPCSE12: Getting into FLOW3
IPCSE12: Getting into FLOW3IPCSE12: Getting into FLOW3
IPCSE12: Getting into FLOW3
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
 
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
 
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Bb Tequila Coding Style (Draft)
Bb Tequila Coding Style (Draft)Bb Tequila Coding Style (Draft)
Bb Tequila Coding Style (Draft)
 

Mais de Zend by Rogue Wave Software

Mais de Zend by Rogue Wave Software (20)

Develop microservices in php
Develop microservices in phpDevelop microservices in php
Develop microservices in php
 
Speed and security for your PHP application
Speed and security for your PHP applicationSpeed and security for your PHP application
Speed and security for your PHP application
 
Building and managing applications fast for IBM i
Building and managing applications fast for IBM iBuilding and managing applications fast for IBM i
Building and managing applications fast for IBM i
 
Building web APIs in PHP with Zend Expressive
Building web APIs in PHP with Zend ExpressiveBuilding web APIs in PHP with Zend Expressive
Building web APIs in PHP with Zend Expressive
 
To PHP 7 and beyond
To PHP 7 and beyondTo PHP 7 and beyond
To PHP 7 and beyond
 
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018) Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
 
The Sodium crypto library of PHP 7.2 (PHP Day 2018)
The Sodium crypto library of PHP 7.2 (PHP Day 2018)The Sodium crypto library of PHP 7.2 (PHP Day 2018)
The Sodium crypto library of PHP 7.2 (PHP Day 2018)
 
Develop web APIs in PHP using middleware with Expressive (Code Europe)
Develop web APIs in PHP using middleware with Expressive (Code Europe)Develop web APIs in PHP using middleware with Expressive (Code Europe)
Develop web APIs in PHP using middleware with Expressive (Code Europe)
 
Middleware web APIs in PHP 7.x
Middleware web APIs in PHP 7.xMiddleware web APIs in PHP 7.x
Middleware web APIs in PHP 7.x
 
Ongoing management of your PHP 7 application
Ongoing management of your PHP 7 applicationOngoing management of your PHP 7 application
Ongoing management of your PHP 7 application
 
Developing web APIs using middleware in PHP 7
Developing web APIs using middleware in PHP 7Developing web APIs using middleware in PHP 7
Developing web APIs using middleware in PHP 7
 
The Docker development template for PHP
The Docker development template for PHPThe Docker development template for PHP
The Docker development template for PHP
 
The most exciting features of PHP 7.1
The most exciting features of PHP 7.1The most exciting features of PHP 7.1
The most exciting features of PHP 7.1
 
Unit testing for project managers
Unit testing for project managersUnit testing for project managers
Unit testing for project managers
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
 
Deploying PHP apps on the cloud
Deploying PHP apps on the cloudDeploying PHP apps on the cloud
Deploying PHP apps on the cloud
 
Data is dead. Long live data!
Data is dead. Long live data! Data is dead. Long live data!
Data is dead. Long live data!
 
Optimizing performance
Optimizing performanceOptimizing performance
Optimizing performance
 
Resolving problems & high availability
Resolving problems & high availabilityResolving problems & high availability
Resolving problems & high availability
 
Developing apps faster
Developing apps fasterDeveloping apps faster
Developing apps faster
 

Último

TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
FIDO Alliance
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
FIDO Alliance
 

Último (20)

Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxCyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
How to Check GPS Location with a Live Tracker in Pakistan
How to Check GPS Location with a Live Tracker in PakistanHow to Check GPS Location with a Live Tracker in Pakistan
How to Check GPS Location with a Live Tracker in Pakistan
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
Navigating the Large Language Model choices_Ravi Daparthi
Navigating the Large Language Model choices_Ravi DaparthiNavigating the Large Language Model choices_Ravi Daparthi
Navigating the Large Language Model choices_Ravi Daparthi
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 

Using PHP 5.3 Namespaces for Fame and Fortune

  • 1. Using PHP 5.3 Namespaces for Fame and Fortune Matthew Weier O'Phinney Project Lead, Zend Framework © All rights reserved. Zend Technologies, Inc.
  • 2. What are “namespaces”? © All rights reserved. Zend Technologies, Inc.
  • 3. What are “namespaces”? "A way in which to group related classes, functions and constants" – http://php.net/namespace © All rights reserved. Zend Technologies, Inc.
  • 4. Basics © All rights reserved. Zend Technologies, Inc.
  • 5. Namespace Separator “” Get over it! © All rights reserved. Zend Technologies, Inc.
  • 6. What can live in namespaces ● Classes ● Constants ● Functions © All rights reserved. Zend Technologies, Inc.
  • 7. Declaring namespaces ● Single line declaration namespace Foo; © All rights reserved. Zend Technologies, Inc.
  • 8. Declaring namespaces ● Block declaration namespace Foo { } namespace Bar { } © All rights reserved. Zend Technologies, Inc.
  • 9. Subnamespaces ● Separate the subnamespaces using the namespace separator namespace FooBar; namespace FooBarBaz; © All rights reserved. Zend Technologies, Inc.
  • 10. Referring to namespaced elements ● From non-namespaced code: $class = new FooBarClass(); $class = new FooBarBazClass(); FoobarFunc(); // function call $val = FooBAT; // constant value © All rights reserved. Zend Technologies, Inc.
  • 11. Referring to namespaced elements ● From code using the same namespace: namespace Foo; $class = new BarClass(); $class = new BarBazClass(); barFunc(); // function call $val = BAT; // constant value © All rights reserved. Zend Technologies, Inc.
  • 12. Referring to namespaced elements ● From code in a different namespace: namespace Bar; $class = new FooBarClass(); $class = new FooBarBazClass(); FoobarFunc(); // function call $val = FooBAT; // constant value © All rights reserved. Zend Technologies, Inc.
  • 13. Using namespaced code: ● Prefixing with a namespace separator resolves as a fully qualified name ● Resolution order: ▶ Globally qualified: known; otherwise: ▶ Current namespace, or relative to it (Classes, functions, constants) ▶ Global namespace (functions, constants) © All rights reserved. Zend Technologies, Inc.
  • 14. Importing namespaces ● A way to bring code from another namespace into the current namespace. ● Import: ▶ Classes ▶ Other namespaces ● Keyword used is use © All rights reserved. Zend Technologies, Inc.
  • 15. Importing namespaces namespace Foo; class Bar {} namespace Bar; use Foo; // imports namespace use FooBar; // imports class © All rights reserved. Zend Technologies, Inc.
  • 16. Using imported code namespace Bar; use Foo; // imports namespace $bar = new FooBar(); namespace Bar; use FooBar; // imports class $bar = new Bar(); © All rights reserved. Zend Technologies, Inc.
  • 17. Aliasing ● "import namespace or class, but refer to it using this name" ● PHP utilizes the as keyword to alias © All rights reserved. Zend Technologies, Inc.
  • 18. Aliasing namespace Bar; use Foo as f; $bar = new fBar(); namespace Bar; use FooBar as bar; $bar = new bar(); © All rights reserved. Zend Technologies, Inc.
  • 19. Make typehinting more semantic! namespace App; use ZendEventManagerEventManager as Events; class Foo { public function events(Events $events = null) { if ($events instanceof Events) { $this->events = $events; } elseif (!$this->events instanceof Events) { $this->events = new Events(__CLASS__); } return $this->events; } } © All rights reserved. Zend Technologies, Inc.
  • 20. Importing multiple namespaces/classes ● Multiple use statements namespace BazBat; use Foo; use Bar; © All rights reserved. Zend Technologies, Inc.
  • 21. Importing multiple namespaces/classes ● Or use a comma (“,”) to separate statements namespace BazBat; use Foo, Bar; © All rights reserved. Zend Technologies, Inc.
  • 22. Importing multiple namespaces/classes ● With aliases namespace BazBat; use Foo as f, // aliased Bar; // not aliased © All rights reserved. Zend Technologies, Inc.
  • 23. What namespace are you in? ● __NAMESPACE__ © All rights reserved. Zend Technologies, Inc.
  • 24. Comprehensive example ● The setup: namespace FooBar; const BAZ = 1; function baz($data) {} class Baz {} namespace FooBaz; const BAZ = 2; function baz($data) {} class Baz {} © All rights reserved. Zend Technologies, Inc.
  • 25. Comprehensive example namespace Test; use FooBarBaz as BarBaz, FooBaz; const BAZ = 3; echo BAZ; // 3 echo BazBAZ; // 2 echo FooBarBAZ; // 1 $baz = new BarBaz(); // FooBarBaz $baz = new Baz(); // E_FATAL (no matching class) $baz = new BazBaz(); // FooBazBaz baz($baz); // E_FATAL (no matching function in // current namespace) Bazbaz($baz); // FooBazbaz() © All rights reserved. Zend Technologies, Inc.
  • 26. Pitfalls © All rights reserved. Zend Technologies, Inc.
  • 27. Referencing namespaced code in strings ● Classes, constants, and functions referenced in a string MUST be fully qualified ● No namespace separator prefix is necessary © All rights reserved. Zend Technologies, Inc.
  • 28. Referencing namespaced code in strings ● Example 1 namespace Foo; // Assume FooBarBaz is a defined class $class = 'BarBaz'; $o = new $class; // E_FATAL; can't find // relative names $class = 'FooBarBaz'; $o = new $class; // Success $class = 'FooBarBaz'; $o = new $class; // Also success, // but not necessary © All rights reserved. Zend Technologies, Inc.
  • 29. Referencing namespaced code in strings ● Example 2 namespace Foo; // Assume FooBarBaz is a defined class $class = 'BarBaz'; if ($o instanceof $class) { } // Fails; can't // resolve class $class = 'FooBarBaz'; if ($o instanceof $class) { } // Success © All rights reserved. Zend Technologies, Inc.
  • 30. Why use namespaces? © All rights reserved. Zend Technologies, Inc.
  • 31. Code Organization: Filesystem ● Namespace separator has an affinity for the directory separator ● Suggests a 1:1 relationship with file system namespace FooBar; class Baz {} /* Foo/Bar/Baz.php (*nix) FooBarBaz.php (Windows) */ © All rights reserved. Zend Technologies, Inc.
  • 32. Code Organization: By Responsibility ● Interfaces ▶ Use cases: ● instanceof: $class instanceof Adapter ● implements: SomeClass implements Adapter ▶ Natural language is easiest to understand ▶ Natural language suggests a hierarchy © All rights reserved. Zend Technologies, Inc.
  • 33. Code Organization: By Responsibility namespace ComponentAdapter; use ComponentAdapter; class ConcreteAdapter implements Adapter {} ● interface ComponentAdapter in Component/Adapter.php ● class ComponentAdapterConcreteAdapter in Component/Adapter/ConcreteAdapter.php © All rights reserved. Zend Technologies, Inc.
  • 34. Code Organization: By Responsibility ● Takeaway: we're referencing the capabilities, not the language type © All rights reserved. Zend Technologies, Inc.
  • 35. Readability ● When within a namespace, reference classes directly, keeping usage succinct namespace ZendHttp; $client = new Client(); © All rights reserved. Zend Technologies, Inc.
  • 36. Readability ● Importing and aliasing make names more succinct namespace Application; use ZendHttpClient as HttpClient, ZendLoggerLogger; $client = new HttpClient(); $log = new Logger(); © All rights reserved. Zend Technologies, Inc.
  • 37. Readability ● Aliasing allows giving names context namespace ApplicationController; use ZendControllerAction as ActionController; class FooController extends ActionController {} © All rights reserved. Zend Technologies, Inc.
  • 38. Dependency declarations ● Suggestion: import every class outside the current namespace that you consume namespace ApplicationController; use ZendControllerAction as ActionController, MyORMMapper as DataMapper, MyEntityBlogEntry, ZendEventManagerEventManager; © All rights reserved. Zend Technologies, Inc.
  • 39. Dependency declarations ● Imports are hints to the interpreter, and don't cost anything ● Helps to document dependencies up front ● Allows static analysis to determine dependencies © All rights reserved. Zend Technologies, Inc.
  • 40. Resources © All rights reserved. Zend Technologies, Inc.
  • 41. PHP Manual: http://php.net/namespace © All rights reserved. Zend Technologies, Inc.
  • 42. Webinar To watch the recorded webinar, please go to http://www.zend.com/en/webinar/Framework/ 70170000000bWGR-PHP-Namespaces.flv or http://bit.ly/pcVMKR (a short registration is required) © All rights reserved. Zend Technologies, Inc.