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

Unit 1-introduction to perl
Unit 1-introduction to perlUnit 1-introduction to perl
Unit 1-introduction to perlsana mateen
 
PHP Underground Session 1: The Basics
PHP Underground Session 1: The BasicsPHP Underground Session 1: The Basics
PHP Underground Session 1: The BasicsRobin Hawkes
 
Mastering Namespaces in PHP
Mastering Namespaces in PHPMastering Namespaces in PHP
Mastering Namespaces in PHPNick Belhomme
 
PHPBootcamp - Zend Framework
PHPBootcamp - Zend FrameworkPHPBootcamp - Zend Framework
PHPBootcamp - Zend Frameworkthomasw
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners PerlDave Cross
 
Yapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line PerlYapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line PerlBruce Gray
 
PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)Win Yu
 
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)Roy Zimmer
 
Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaEdureka!
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?Nick Belhomme
 
Extending Zend Framework
Extending Zend FrameworkExtending Zend Framework
Extending Zend FrameworkPHPBelgium
 
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 ProgrammingUtkarsh Sengar
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009cwarren
 

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

Zend Framework 2 quick start
Zend Framework 2 quick startZend Framework 2 quick start
Zend Framework 2 quick startEnrico 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)
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)ZFConf Conference
 
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 2Enrico Zimuel
 
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
 
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 v2Acácio Oliveira
 
Getting Into FLOW3 (DPC12)
Getting Into FLOW3 (DPC12)Getting Into FLOW3 (DPC12)
Getting Into FLOW3 (DPC12)Robert Lemke
 
New Stuff In Php 5.3
New Stuff In Php 5.3New Stuff In Php 5.3
New Stuff In Php 5.3Chris Chubb
 
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)James Titcumb
 
PHP Introduction and Training Material
PHP Introduction and Training MaterialPHP Introduction and Training Material
PHP Introduction and Training MaterialManoj kumar
 
IPCSE12: Getting into FLOW3
IPCSE12: Getting into FLOW3IPCSE12: Getting into FLOW3
IPCSE12: Getting into FLOW3Robert Lemke
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Guillaume Laforge
 
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)James Titcumb
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboardsDenis Ristic
 
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)James Titcumb
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for javamaheshm1206
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar 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

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 iZend by Rogue Wave Software
 
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) Zend by Rogue Wave Software
 
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)Zend by Rogue Wave Software
 
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)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

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

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.