SlideShare a Scribd company logo
1 of 54
Magento




AOP, Metaprogramming, Codeg
eneration
Or the way of throwing elephants to a blackbox.



                                                  Serge Smertin
Magento




About
    Zend Certified Engineer
    Senior Sw. Engineer @ EPAM
    PHP since 2005
    CakePHP since 2007
    Zend Framework since 2008
    Yii since 2010
    Symfony 2.0 since 2011
    Can also tell you something
     about pros & cons of
     CodeIgniner, Drupal, Wordpress
Magento




Agenda

 Inversion of control
 Metaprogramming
 Unexpected & Interesting
 Codegeneration
 Real life usage
Magento




Design matters: SOLID
 5 principles of enterprise object-oriented
  design:
  • Single responsibility
  • Open-close
  • Liskov substitution
  • Interface segregation
  • Dependency injection
Magento




Dependency Injection
 Only possible with some kind of service locator
 Makes able to lazy initialize all resource
  dependencies
 Simplify debugging and development
 Simplify existing components extension and
  integration
 Dependency injection in PHP 5.3/5.4
  http://slidesha.re/vE8Wyp
Magento




Service locators in PHP

 Most of them require build stage
 For performance reasons they
  leverage codegeneration
 Require dependency configuration in
  some of the established ways
 Heavily utilize Reflection API
Magento




Why building?
Magento




Pimple
  73 lines of PHP code
  Use closures heavily
  Made as fun proof of concept
  Good for little projects
  Base of Silex microframework

  URLS
   • Pimple: http://pimple.sensiolabs.org/
   • Silex project: http://silex.sensiolabs.org/
Magento




Symfony 2 DI Component
    Mature production ready
    Stores configuration within XML, YAML or annotations
    Support for event observers
    Support for custom service tagging
    Scopes
    Require build step for deploy
    Supported by Sensio Labs. Paid subscriptions available
    Could be integrated through PEAR
    Easy 

  URLS go here:
     • DI for PHP 5.2 - http://bit.ly/uGt8CK
     • PEAR channel: http://pear.symfony.com/
     • Service Container - http://bit.ly/s7F8HF
Magento




Some cookies: CLI
  Some tasks could be
   done through CLI easier
  Cron?
  Daemons?
  Continuous integration?
  Expose services to
   console?
Magento




cli:call
   What about writing
    custom command for
    accessing nearly
    every defined service
    in container for
    isolated working?

 $ ./app/console cli:call
 service.name methodName
 [arg1, arg2, arg3, …]
Magento




Metaprogramming

 Is how programs are self-aware
 Is not recommended to use at run time
 Is the art of operating metadata
 Is black magic processed at build step
 Is possible with PHP 5
 Is making the code shorter
Magento




Metadata

 XML files
 YAML files
 Database
 Naming conventions
Magento




Metadata

 XML files
 YAML files
 Database
 Naming conventions

 … boring.
Magento




Metadata

 XML files     PHP doc comments
 YAML files    PHP code itself
 Database      Reflection
 Naming        Annotations
  conventions   SQL code
Magento




Reflection API

   A way of retrieving information about
    parameters for a class method
   A way of accessing private property of a
    parent class
   A way of passing method parameters by name
   Another way of making callback
   Other more or less interesting ways of
    application
Magento




Annotation magic
    Actually are custom docblock tags with some extend
    Some kind of XDoclet API for PHP
    Some other couple of words here
    Some frameworks endorse usage: Symfony2 & FLOW3
    Couple of existing solutions available
      • Regular expressions 
      • PHPUnit
      • ZendReflectionDocblockTag (just extended PCRE, actually)
      • Doctrine annotation reader (parser-based method)

  Links:
     • Doctrine Annotations Reference http://bit.ly/s6kQfh
     • An article of 2008 http://bit.ly/uT1v2U
     • XDoclet overview of 2005 http://bit.ly/tYy8pa
Magento




Tokenization
   Just token_get_all() and
    be insane

   Build a classmap file with
    namespace information
   Generate unit test
    skeletons
   Put all TODO’s in
    comments as tickets to
    Jira
   Some of more
    sophisticated things I
    haven’t thought about
Magento




SQL code: annotations. Why not?
Magento




SQL: Sharding. Annotations?..
   Get meta-info about sharded connection to
    use from query directly
   Or parse the query, but little longer

   /*entity customer://1234 */
    SELECT name FROM customer WHERE
    id = 1234

   Database Scale http://slidesha.re/vC1i9x
   Sharding for startups http://bit.ly/vLa68N
Magento




Doctrine Common: Annotation reader
  Annotation is a class
  Any number of properties could be passed to
   constructor
  Nesting
  Short forms
  Takes time to process
Magento




Takes time to process?
 All configuration is read from DI container
 DI container is regenerated upon build
 Dev. env. regenerates DI each request
 Prod. env. reads cached DI
 Annotations aren’t processed in prod. env.
 PROFIT!
Magento




… well, mostly…

 Not all is processed on build
 Annotations are good for event
  listeners *
 Convenient way for storing meta-
  information within the code

* Classes defined as services and tagged with special event hooks. Later
transformed to code in some of generated DIC methods.
Magento




Processing annotations
1. Create class implementing
   SymfonyComponentDependencyInjectionCompiler
   CompilerPassInterface
2. Collect annotations via reader
3. Save processed metadata in container via
   ContainerBuilder::setParameter()
4. Add build(ContainerBuilder $cb) method to bundle
   main class
5. Add kernel.* event observers
6. PROFIT
Magento




Real life: collecting metadata
Magento




Autowiring
  Inject serviced needed to places needed
  Reflection-heavy
  Hard, but possible for PHP
  MVC simplifying 
  Ready solutions
    • Autowiring Bundle – http://bit.ly/uDTKYi
    • JMSDiExtraBundle – http://bit.ly/t7pP89
    • FLOW3 autowiring – http://bit.ly/tcJQ10
Magento




Common now is less: CRON




  • Adding periodical tasks seem somewhat boring
  • With annotated configuration it could be set up in
    seconds
  • This simple annotation will be transformed in
    crontab file to something like
     0 */4 * * * /usr/bin/php /path/to/app/console cli:call
     our.user.service sendNotifications
Magento




Doing things wrong?
Magento




Doing things wrong

  When my IDE* cannot help
   auto completing I'm using
   bad practice programming


 * Netbeans, Eclipse, PHPStorm, .. put your favorite here
Magento




Real life: Autowiring
   Create services with
    simple annotating
    them
   Inject existing services
    to class properties
   Apply name guessing
    strategies

   JMSDiExtraBundle
    used
Magento




Keeping code short
                                                        Configure routes
                                                        inline



                                                         Configure templates
                                                         inline



                                                        Inject only services,
                                                        that the action really
                                                        needs. Recognized by
                                                        IDE directly

                     Return needed variables for view
Magento




grep
 Nice tool to get only those classes
  with annotations & autowiring to
  parse
 True UNIX way
 Or use a class-map file – URL goes
  here
 Done at the build step
Magento




Codegeneration and codedegeneration
  Programs program programs
  As ideal – lets developer develop business logic, not the
   boilerplate
  Programs make pieces of programs
   • RAD tools and frameworks
   • IDE code templates
  Having templates is really good
  Customization is good


  “Code Generation in Action” by Jack Herrington D.
   http://amzn.to/skQzEr
Magento




Use cases
 Project rapid start
 Enterprise stuff
 DB interaction & ORM
 Better unit test skeletons
 Performance
 Code transformation
 Boilerplates & customization
 Bunch of routine stuff …
Magento




Use-case: Generating unit-tests
 Goal: save time creating boilerplate code
  for
   • Initialization of all dependent objects
   • Public methods
   • Possible conditional logic
   • Asserting actual and expected results
   • Mock object methods boilerplate
Magento




How?

Wrapper over token_get_all()
Reflection API
ZendReflection &
 ZendCodeGenerator
Magento




Use-case: proxy generation for performance
  Template engines – compile own markup to PHP
  Symfony DI Component – generates service bootstrap
   in PHP
  JMSSecurityBundle – puts security checking to
   generated proxies
  SymfonyGeneratorBundle – makes writing boilerplate
   CRUD code for controllers and entities faster and
   easier.
  Put your own here.
Magento




Common things
 Framework specific
 Define placeholders
 Extend and Proxy
 Liscov substitution principle
 Have templates, that are editable
 Have an easy way to make own templates
 Regenerate stuff on architecture change
Magento




Existing solutions
 PHP ecosystem
  Symfony2 – SensioGeneratorBundle – http://symfony.com/
  Doctrine2 – two-way ORM/DB generator – http://bit.ly/veIvvm
  ZendFramework – ZendCodeGenerator – http://bit.ly/s7mYHD
  cg-library – http://bit.ly/vtBfk7
  QCodo – interesting RAD generator – http://qcodo.com/
  CakePHP – RAD project start - http://cakephp.org/

 Other
  CodeSmith – http://codesmithtools.com/
 …
Magento




Generating codegenerators
 Have an ideal code sample: R&D
  something nice 
 Get code slice from line X to line Y
 Define common pattern fast
 Get template. Test it. Improve
  sample.
 Apply results of your concept fast
Magento




In 6 months …

 Improve ideal code sample
 Improve template
 Regenerate those hundreds of files
  in seconds with compatibility kept
 PROFIT.
Magento




A tool
  Some internal tool for generating generators, unit tests, fixtures
  Typical usage:
                              Sample file        Start and end lines
            Format
   $ pugooroo tpl RolseService.php 108 118 
                                              Copy output
          --pieces --heredoc --copy 
Pick vars                                     to buffer 
          --function generateStuff
   cogen> Enter code pieces you want to replace       Wrap up to
                                                        function
      user
                Interactive
      group
                CLI app!11
      Group

 cogen> Enter alias for 'user' [piece0]: FIRST
 cogen> Enter alias for 'group' [piece1]: SECOND
 cogen> Enter alias for 'Group' [piece2]: SECOND_CAMELCASED
Magento




And typical result
 function generateStuff ($FIRST, $SECOND, $SECOND_CAMELCASED) {
 $tmpl = <<<EOF
     ${$FIRST}Counts = array();
     while ($row = $stmt->fetchObject()) {
       ${$FIRST}Counts[(int) $row->{$SECOND}_id] = (int) $row-
 >num_{$FIRST}s;
     }

    foreach(${$SECOND}s as ${$SECOND}) {
      /* @var ${$SECOND} {$SECOND_CAMELCASED} */
      if(isset (${$FIRST}Counts[${$SECOND}->getId()])) {
        ${$SECOND}->setUsercount(${$FIRST}Counts[${$SECOND}->getId()]);
      }
    }

 EOF;
 return $tmpl;
 }
Magento




CLI: interaction & copy to buffer
 Interaction: streams
   • php://stdin
   • php://stdout

 Copy to buffer from CLI:
  • MacOS: echo $res | pbcopy
  • Linux: echo $res | xclip …
  • Windows: 
Magento




The more sophisticated things
 #Joined array turns out to be more flexible than HEREDOC:
 function generateStuff ($FIRST, $SECOND, $SECOND_CAMELCASED, $needsSomething =
 true) {
         $tmpl = array();
         $tmpl[] = "     ${$FIRST}Counts = array();";
         $tmpl[] = "     while ($row = $stmt->fetchObject()) {";
         $tmpl[] = "        ${$FIRST}Counts[(int) $row->{$SECOND}_id] = (int) $row-
 >num_{$FIRST}s;";
         $tmpl[] = "     }";
         $tmpl[] = "     ";
         if($needsSomething) {
                   $tmpl[] = "     foreach(${$SECOND}s as ${$SECOND}) {";
                   $tmpl[] = "       if(isset (${$FIRST}Counts[${$SECOND}-
 >getId()])) {";
                   $tmpl[] = "         ${$SECOND}-
 >setUsercount(${$FIRST}Counts[${$SECOND}->getId()]);";
                   $tmpl[] = "       }";
                   $tmpl[] = "     }";
                   $tmpl[] = "";
         }
         $tmpl = join("n", $tmpl);

         return $tmpl;
 }
Magento




Real life: tagged keys in cache
 Goal:
   • Resultset of a method could be cached
   • Resultset is dependent on other resultsets validity
   • If dependent resultset becomes invalid – invalidate only
     needed keys
   • Perform application-wide substitutions like currently logged in
     user and etc
   • Make adding and removing cache really easy
 Bad things
   • Require complex code to maintain
   • Hard to read
Magento




Solution
  Java EhCache framework – http://ehcache.org/
  @Cacheable & @TriggersRemove with tagging-
   specific features
  Generate code for proxy class
  Substitute original class within inversion of
   control container
  Call the same method without any API change
  Turn off caching when needed
Magento




Slight changes to code
Magento




Generated code for caching
Magento




Real life: add security restrictions
  Goal:
   • Protect methods of service from unauthorized access
   • Have access granularity to actions of controller
   • Limit access for modifying particular entities
   • Make it easy
  Solutions:
   • Symfony2 – JmsSecurityExtraBundle – http://bit.ly/sX0hN6
   • DiExtraBundle – autowiring stuff – http://bit.ly/t7pP89
   • AopBundle – intercept method calls – http://bit.ly/vFqWSD
Magento




Events
Magento




Fast forms & XML




 * Doctrine OXM: http://github.com/doctrine/oxm
Magento




Questions &
 Answers
Magento




Thank you
• http://twitter.com/nf_x
• http://ua.linkedin.com/smertin

More Related Content

What's hot

Titanium Mobile: flexibility vs. performance
Titanium Mobile: flexibility vs. performanceTitanium Mobile: flexibility vs. performance
Titanium Mobile: flexibility vs. performanceomorandi
 
Zend Framework Getting Started For I5
Zend Framework Getting Started For I5Zend Framework Getting Started For I5
Zend Framework Getting Started For I5ZendCon
 
Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students shafiq sangi
 
20090410 J Spring Pragmatic Model Driven Development In Java Using Smart
20090410   J Spring Pragmatic Model Driven Development In Java Using Smart20090410   J Spring Pragmatic Model Driven Development In Java Using Smart
20090410 J Spring Pragmatic Model Driven Development In Java Using SmartSander Hoogendoorn
 
JavaOne 2009 BOF-5189 Griffon In Depth
JavaOne 2009 BOF-5189 Griffon In DepthJavaOne 2009 BOF-5189 Griffon In Depth
JavaOne 2009 BOF-5189 Griffon In DepthDanno Ferrin
 
Python in the browser
Python in the browserPython in the browser
Python in the browserPyCon Italia
 
C++ API 디자인 - 확장성
C++ API 디자인 - 확장성C++ API 디자인 - 확장성
C++ API 디자인 - 확장성HyeonSeok Choi
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01Jay Palit
 
Wakanda: NoSQL for Model-Driven Web applications - NoSQL matters 2012
Wakanda: NoSQL for Model-Driven Web applications - NoSQL matters 2012Wakanda: NoSQL for Model-Driven Web applications - NoSQL matters 2012
Wakanda: NoSQL for Model-Driven Web applications - NoSQL matters 2012Alexandre Morgaut
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operatorkamal kotecha
 
Adopting Agile Tools & Methods In A Legacy Context
Adopting Agile Tools & Methods In A Legacy ContextAdopting Agile Tools & Methods In A Legacy Context
Adopting Agile Tools & Methods In A Legacy ContextXavier Warzee
 
Java j2ee interview_questions
Java j2ee interview_questionsJava j2ee interview_questions
Java j2ee interview_questionsppratik86
 
AD106 - IBM Lotus Domino XPages anywhere - Write them once, See them Everywhere
AD106 - IBM Lotus Domino XPages anywhere - Write them once, See them EverywhereAD106 - IBM Lotus Domino XPages anywhere - Write them once, See them Everywhere
AD106 - IBM Lotus Domino XPages anywhere - Write them once, See them EverywhereStephan H. Wissel
 

What's hot (19)

Java vs .Net
Java vs .NetJava vs .Net
Java vs .Net
 
Titanium Mobile: flexibility vs. performance
Titanium Mobile: flexibility vs. performanceTitanium Mobile: flexibility vs. performance
Titanium Mobile: flexibility vs. performance
 
Zend Framework Getting Started For I5
Zend Framework Getting Started For I5Zend Framework Getting Started For I5
Zend Framework Getting Started For I5
 
Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students
 
Dacj 2-2 a
Dacj 2-2 aDacj 2-2 a
Dacj 2-2 a
 
20090410 J Spring Pragmatic Model Driven Development In Java Using Smart
20090410   J Spring Pragmatic Model Driven Development In Java Using Smart20090410   J Spring Pragmatic Model Driven Development In Java Using Smart
20090410 J Spring Pragmatic Model Driven Development In Java Using Smart
 
JavaOne 2009 BOF-5189 Griffon In Depth
JavaOne 2009 BOF-5189 Griffon In DepthJavaOne 2009 BOF-5189 Griffon In Depth
JavaOne 2009 BOF-5189 Griffon In Depth
 
Python in the browser
Python in the browserPython in the browser
Python in the browser
 
C++ API 디자인 - 확장성
C++ API 디자인 - 확장성C++ API 디자인 - 확장성
C++ API 디자인 - 확장성
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01
 
Wakanda: NoSQL for Model-Driven Web applications - NoSQL matters 2012
Wakanda: NoSQL for Model-Driven Web applications - NoSQL matters 2012Wakanda: NoSQL for Model-Driven Web applications - NoSQL matters 2012
Wakanda: NoSQL for Model-Driven Web applications - NoSQL matters 2012
 
Portlet factory 101
Portlet factory 101Portlet factory 101
Portlet factory 101
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
 
Adopting Agile Tools & Methods In A Legacy Context
Adopting Agile Tools & Methods In A Legacy ContextAdopting Agile Tools & Methods In A Legacy Context
Adopting Agile Tools & Methods In A Legacy Context
 
Java j2ee interview_questions
Java j2ee interview_questionsJava j2ee interview_questions
Java j2ee interview_questions
 
Project Zero JavaOne 2008
Project Zero JavaOne 2008Project Zero JavaOne 2008
Project Zero JavaOne 2008
 
Tfs Per Team Agili
Tfs Per Team AgiliTfs Per Team Agili
Tfs Per Team Agili
 
AD106 - IBM Lotus Domino XPages anywhere - Write them once, See them Everywhere
AD106 - IBM Lotus Domino XPages anywhere - Write them once, See them EverywhereAD106 - IBM Lotus Domino XPages anywhere - Write them once, See them Everywhere
AD106 - IBM Lotus Domino XPages anywhere - Write them once, See them Everywhere
 

Viewers also liked

Big Data is changing abruptly, and where it is likely heading
Big Data is changing abruptly, and where it is likely headingBig Data is changing abruptly, and where it is likely heading
Big Data is changing abruptly, and where it is likely headingPaco Nathan
 
Reactive Streams 1.0 and Akka Streams
Reactive Streams 1.0 and Akka StreamsReactive Streams 1.0 and Akka Streams
Reactive Streams 1.0 and Akka StreamsDean Wampler
 
Reactive dashboard’s using apache spark
Reactive dashboard’s using apache sparkReactive dashboard’s using apache spark
Reactive dashboard’s using apache sparkRahul Kumar
 
Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...
Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...
Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...Anton Kirillov
 
(BDT310) Big Data Architectural Patterns and Best Practices on AWS
(BDT310) Big Data Architectural Patterns and Best Practices on AWS(BDT310) Big Data Architectural Patterns and Best Practices on AWS
(BDT310) Big Data Architectural Patterns and Best Practices on AWSAmazon Web Services
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginnerskenbot
 

Viewers also liked (6)

Big Data is changing abruptly, and where it is likely heading
Big Data is changing abruptly, and where it is likely headingBig Data is changing abruptly, and where it is likely heading
Big Data is changing abruptly, and where it is likely heading
 
Reactive Streams 1.0 and Akka Streams
Reactive Streams 1.0 and Akka StreamsReactive Streams 1.0 and Akka Streams
Reactive Streams 1.0 and Akka Streams
 
Reactive dashboard’s using apache spark
Reactive dashboard’s using apache sparkReactive dashboard’s using apache spark
Reactive dashboard’s using apache spark
 
Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...
Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...
Data processing platforms architectures with Spark, Mesos, Akka, Cassandra an...
 
(BDT310) Big Data Architectural Patterns and Best Practices on AWS
(BDT310) Big Data Architectural Patterns and Best Practices on AWS(BDT310) Big Data Architectural Patterns and Best Practices on AWS
(BDT310) Big Data Architectural Patterns and Best Practices on AWS
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginners
 

Similar to Aop, Metaprogramming and codegeneration with PHP

php[world] Magento101
php[world] Magento101php[world] Magento101
php[world] Magento101Mathew Beane
 
Madison PHP - Getting Started with Magento 2
Madison PHP - Getting Started with Magento 2Madison PHP - Getting Started with Magento 2
Madison PHP - Getting Started with Magento 2Mathew Beane
 
Php Frameworks
Php FrameworksPhp Frameworks
Php FrameworksRyan Davis
 
Jan Burkl - Zend & Magento
Jan Burkl - Zend & MagentoJan Burkl - Zend & Magento
Jan Burkl - Zend & MagentoGuido X Jansen
 
Vue3: nuove funzionalità, differenze e come migrare
Vue3: nuove funzionalità, differenze e come migrareVue3: nuove funzionalità, differenze e come migrare
Vue3: nuove funzionalità, differenze e come migrareAndrea Campaci
 
MidwestPHP - Getting Started with Magento 2
MidwestPHP - Getting Started with Magento 2MidwestPHP - Getting Started with Magento 2
MidwestPHP - Getting Started with Magento 2Mathew Beane
 
Monorail presentation at WebDevelopersCommunity, Feb 1, 2009
Monorail presentation at WebDevelopersCommunity, Feb 1, 2009Monorail presentation at WebDevelopersCommunity, Feb 1, 2009
Monorail presentation at WebDevelopersCommunity, Feb 1, 2009ken.egozi
 
Optimizing Magento Performance with Zend Server
Optimizing Magento Performance with Zend ServerOptimizing Magento Performance with Zend Server
Optimizing Magento Performance with Zend Servervarien
 
Rock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsRock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsAOE
 
Zendcon magento101
Zendcon magento101Zendcon magento101
Zendcon magento101Mathew Beane
 
Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with RailsPaul Gallagher
 
IDE and Toolset For Magento Development
IDE and Toolset For Magento DevelopmentIDE and Toolset For Magento Development
IDE and Toolset For Magento DevelopmentAbid Malik
 
Application development using Zend Framework
Application development using Zend FrameworkApplication development using Zend Framework
Application development using Zend FrameworkMahmud Ahsan
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsMarcelo Pinheiro
 
Gerrit linuxtag2011
Gerrit linuxtag2011Gerrit linuxtag2011
Gerrit linuxtag2011thkoch
 
WSO2Con EU 2015: Keynote - The Containerization of the Developer Workspace
WSO2Con EU 2015: Keynote - The Containerization of the Developer WorkspaceWSO2Con EU 2015: Keynote - The Containerization of the Developer Workspace
WSO2Con EU 2015: Keynote - The Containerization of the Developer WorkspaceWSO2
 
20211202 North America DevOps Group NADOG Adapting to Covid With Serverless C...
20211202 North America DevOps Group NADOG Adapting to Covid With Serverless C...20211202 North America DevOps Group NADOG Adapting to Covid With Serverless C...
20211202 North America DevOps Group NADOG Adapting to Covid With Serverless C...Craeg Strong
 
Codecoon - A technical Case Study
Codecoon - A technical Case StudyCodecoon - A technical Case Study
Codecoon - A technical Case StudyMichael Lihs
 

Similar to Aop, Metaprogramming and codegeneration with PHP (20)

php[world] Magento101
php[world] Magento101php[world] Magento101
php[world] Magento101
 
Madison PHP - Getting Started with Magento 2
Madison PHP - Getting Started with Magento 2Madison PHP - Getting Started with Magento 2
Madison PHP - Getting Started with Magento 2
 
Php Frameworks
Php FrameworksPhp Frameworks
Php Frameworks
 
Jan Burkl - Zend & Magento
Jan Burkl - Zend & MagentoJan Burkl - Zend & Magento
Jan Burkl - Zend & Magento
 
.net Framework
.net Framework.net Framework
.net Framework
 
Vue3: nuove funzionalità, differenze e come migrare
Vue3: nuove funzionalità, differenze e come migrareVue3: nuove funzionalità, differenze e come migrare
Vue3: nuove funzionalità, differenze e come migrare
 
MidwestPHP - Getting Started with Magento 2
MidwestPHP - Getting Started with Magento 2MidwestPHP - Getting Started with Magento 2
MidwestPHP - Getting Started with Magento 2
 
Monorail presentation at WebDevelopersCommunity, Feb 1, 2009
Monorail presentation at WebDevelopersCommunity, Feb 1, 2009Monorail presentation at WebDevelopersCommunity, Feb 1, 2009
Monorail presentation at WebDevelopersCommunity, Feb 1, 2009
 
Optimizing Magento Performance with Zend Server
Optimizing Magento Performance with Zend ServerOptimizing Magento Performance with Zend Server
Optimizing Magento Performance with Zend Server
 
green
greengreen
green
 
Rock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsRock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment Workflows
 
Zendcon magento101
Zendcon magento101Zendcon magento101
Zendcon magento101
 
Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with Rails
 
IDE and Toolset For Magento Development
IDE and Toolset For Magento DevelopmentIDE and Toolset For Magento Development
IDE and Toolset For Magento Development
 
Application development using Zend Framework
Application development using Zend FrameworkApplication development using Zend Framework
Application development using Zend Framework
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability Systems
 
Gerrit linuxtag2011
Gerrit linuxtag2011Gerrit linuxtag2011
Gerrit linuxtag2011
 
WSO2Con EU 2015: Keynote - The Containerization of the Developer Workspace
WSO2Con EU 2015: Keynote - The Containerization of the Developer WorkspaceWSO2Con EU 2015: Keynote - The Containerization of the Developer Workspace
WSO2Con EU 2015: Keynote - The Containerization of the Developer Workspace
 
20211202 North America DevOps Group NADOG Adapting to Covid With Serverless C...
20211202 North America DevOps Group NADOG Adapting to Covid With Serverless C...20211202 North America DevOps Group NADOG Adapting to Covid With Serverless C...
20211202 North America DevOps Group NADOG Adapting to Covid With Serverless C...
 
Codecoon - A technical Case Study
Codecoon - A technical Case StudyCodecoon - A technical Case Study
Codecoon - A technical Case Study
 

Recently uploaded

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
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
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
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
 
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
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
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
 

Recently uploaded (20)

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
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
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
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
 
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.
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
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
 

Aop, Metaprogramming and codegeneration with PHP

  • 1. Magento AOP, Metaprogramming, Codeg eneration Or the way of throwing elephants to a blackbox. Serge Smertin
  • 2. Magento About  Zend Certified Engineer  Senior Sw. Engineer @ EPAM  PHP since 2005  CakePHP since 2007  Zend Framework since 2008  Yii since 2010  Symfony 2.0 since 2011  Can also tell you something about pros & cons of CodeIgniner, Drupal, Wordpress
  • 3. Magento Agenda Inversion of control Metaprogramming Unexpected & Interesting Codegeneration Real life usage
  • 4. Magento Design matters: SOLID 5 principles of enterprise object-oriented design: • Single responsibility • Open-close • Liskov substitution • Interface segregation • Dependency injection
  • 5. Magento Dependency Injection Only possible with some kind of service locator Makes able to lazy initialize all resource dependencies Simplify debugging and development Simplify existing components extension and integration Dependency injection in PHP 5.3/5.4 http://slidesha.re/vE8Wyp
  • 6. Magento Service locators in PHP Most of them require build stage For performance reasons they leverage codegeneration Require dependency configuration in some of the established ways Heavily utilize Reflection API
  • 8. Magento Pimple  73 lines of PHP code  Use closures heavily  Made as fun proof of concept  Good for little projects  Base of Silex microframework  URLS • Pimple: http://pimple.sensiolabs.org/ • Silex project: http://silex.sensiolabs.org/
  • 9. Magento Symfony 2 DI Component  Mature production ready  Stores configuration within XML, YAML or annotations  Support for event observers  Support for custom service tagging  Scopes  Require build step for deploy  Supported by Sensio Labs. Paid subscriptions available  Could be integrated through PEAR  Easy   URLS go here: • DI for PHP 5.2 - http://bit.ly/uGt8CK • PEAR channel: http://pear.symfony.com/ • Service Container - http://bit.ly/s7F8HF
  • 10. Magento Some cookies: CLI  Some tasks could be done through CLI easier  Cron?  Daemons?  Continuous integration?  Expose services to console?
  • 11. Magento cli:call  What about writing custom command for accessing nearly every defined service in container for isolated working? $ ./app/console cli:call service.name methodName [arg1, arg2, arg3, …]
  • 12. Magento Metaprogramming Is how programs are self-aware Is not recommended to use at run time Is the art of operating metadata Is black magic processed at build step Is possible with PHP 5 Is making the code shorter
  • 13. Magento Metadata XML files YAML files Database Naming conventions
  • 14. Magento Metadata XML files YAML files Database Naming conventions … boring.
  • 15. Magento Metadata XML files PHP doc comments YAML files PHP code itself Database Reflection Naming Annotations conventions SQL code
  • 16. Magento Reflection API  A way of retrieving information about parameters for a class method  A way of accessing private property of a parent class  A way of passing method parameters by name  Another way of making callback  Other more or less interesting ways of application
  • 17. Magento Annotation magic  Actually are custom docblock tags with some extend  Some kind of XDoclet API for PHP  Some other couple of words here  Some frameworks endorse usage: Symfony2 & FLOW3  Couple of existing solutions available • Regular expressions  • PHPUnit • ZendReflectionDocblockTag (just extended PCRE, actually) • Doctrine annotation reader (parser-based method)  Links: • Doctrine Annotations Reference http://bit.ly/s6kQfh • An article of 2008 http://bit.ly/uT1v2U • XDoclet overview of 2005 http://bit.ly/tYy8pa
  • 18. Magento Tokenization  Just token_get_all() and be insane  Build a classmap file with namespace information  Generate unit test skeletons  Put all TODO’s in comments as tickets to Jira  Some of more sophisticated things I haven’t thought about
  • 20. Magento SQL: Sharding. Annotations?..  Get meta-info about sharded connection to use from query directly  Or parse the query, but little longer  /*entity customer://1234 */ SELECT name FROM customer WHERE id = 1234  Database Scale http://slidesha.re/vC1i9x  Sharding for startups http://bit.ly/vLa68N
  • 21. Magento Doctrine Common: Annotation reader  Annotation is a class  Any number of properties could be passed to constructor  Nesting  Short forms  Takes time to process
  • 22. Magento Takes time to process? All configuration is read from DI container DI container is regenerated upon build Dev. env. regenerates DI each request Prod. env. reads cached DI Annotations aren’t processed in prod. env. PROFIT!
  • 23. Magento … well, mostly… Not all is processed on build Annotations are good for event listeners * Convenient way for storing meta- information within the code * Classes defined as services and tagged with special event hooks. Later transformed to code in some of generated DIC methods.
  • 24. Magento Processing annotations 1. Create class implementing SymfonyComponentDependencyInjectionCompiler CompilerPassInterface 2. Collect annotations via reader 3. Save processed metadata in container via ContainerBuilder::setParameter() 4. Add build(ContainerBuilder $cb) method to bundle main class 5. Add kernel.* event observers 6. PROFIT
  • 26. Magento Autowiring  Inject serviced needed to places needed  Reflection-heavy  Hard, but possible for PHP  MVC simplifying   Ready solutions • Autowiring Bundle – http://bit.ly/uDTKYi • JMSDiExtraBundle – http://bit.ly/t7pP89 • FLOW3 autowiring – http://bit.ly/tcJQ10
  • 27. Magento Common now is less: CRON • Adding periodical tasks seem somewhat boring • With annotated configuration it could be set up in seconds • This simple annotation will be transformed in crontab file to something like 0 */4 * * * /usr/bin/php /path/to/app/console cli:call our.user.service sendNotifications
  • 29. Magento Doing things wrong When my IDE* cannot help auto completing I'm using bad practice programming * Netbeans, Eclipse, PHPStorm, .. put your favorite here
  • 30. Magento Real life: Autowiring  Create services with simple annotating them  Inject existing services to class properties  Apply name guessing strategies  JMSDiExtraBundle used
  • 31. Magento Keeping code short Configure routes inline Configure templates inline Inject only services, that the action really needs. Recognized by IDE directly Return needed variables for view
  • 32. Magento grep Nice tool to get only those classes with annotations & autowiring to parse True UNIX way Or use a class-map file – URL goes here Done at the build step
  • 33. Magento Codegeneration and codedegeneration  Programs program programs  As ideal – lets developer develop business logic, not the boilerplate  Programs make pieces of programs • RAD tools and frameworks • IDE code templates  Having templates is really good  Customization is good  “Code Generation in Action” by Jack Herrington D. http://amzn.to/skQzEr
  • 34. Magento Use cases Project rapid start Enterprise stuff DB interaction & ORM Better unit test skeletons Performance Code transformation Boilerplates & customization Bunch of routine stuff …
  • 35. Magento Use-case: Generating unit-tests Goal: save time creating boilerplate code for • Initialization of all dependent objects • Public methods • Possible conditional logic • Asserting actual and expected results • Mock object methods boilerplate
  • 36. Magento How? Wrapper over token_get_all() Reflection API ZendReflection & ZendCodeGenerator
  • 37. Magento Use-case: proxy generation for performance  Template engines – compile own markup to PHP  Symfony DI Component – generates service bootstrap in PHP  JMSSecurityBundle – puts security checking to generated proxies  SymfonyGeneratorBundle – makes writing boilerplate CRUD code for controllers and entities faster and easier.  Put your own here.
  • 38. Magento Common things Framework specific Define placeholders Extend and Proxy Liscov substitution principle Have templates, that are editable Have an easy way to make own templates Regenerate stuff on architecture change
  • 39. Magento Existing solutions PHP ecosystem  Symfony2 – SensioGeneratorBundle – http://symfony.com/  Doctrine2 – two-way ORM/DB generator – http://bit.ly/veIvvm  ZendFramework – ZendCodeGenerator – http://bit.ly/s7mYHD  cg-library – http://bit.ly/vtBfk7  QCodo – interesting RAD generator – http://qcodo.com/  CakePHP – RAD project start - http://cakephp.org/ Other  CodeSmith – http://codesmithtools.com/ …
  • 40. Magento Generating codegenerators Have an ideal code sample: R&D something nice  Get code slice from line X to line Y Define common pattern fast Get template. Test it. Improve sample. Apply results of your concept fast
  • 41. Magento In 6 months … Improve ideal code sample Improve template Regenerate those hundreds of files in seconds with compatibility kept PROFIT.
  • 42. Magento A tool  Some internal tool for generating generators, unit tests, fixtures  Typical usage: Sample file Start and end lines Format $ pugooroo tpl RolseService.php 108 118 Copy output --pieces --heredoc --copy Pick vars to buffer  --function generateStuff cogen> Enter code pieces you want to replace Wrap up to function user Interactive group CLI app!11 Group cogen> Enter alias for 'user' [piece0]: FIRST cogen> Enter alias for 'group' [piece1]: SECOND cogen> Enter alias for 'Group' [piece2]: SECOND_CAMELCASED
  • 43. Magento And typical result function generateStuff ($FIRST, $SECOND, $SECOND_CAMELCASED) { $tmpl = <<<EOF ${$FIRST}Counts = array(); while ($row = $stmt->fetchObject()) { ${$FIRST}Counts[(int) $row->{$SECOND}_id] = (int) $row- >num_{$FIRST}s; } foreach(${$SECOND}s as ${$SECOND}) { /* @var ${$SECOND} {$SECOND_CAMELCASED} */ if(isset (${$FIRST}Counts[${$SECOND}->getId()])) { ${$SECOND}->setUsercount(${$FIRST}Counts[${$SECOND}->getId()]); } } EOF; return $tmpl; }
  • 44. Magento CLI: interaction & copy to buffer Interaction: streams • php://stdin • php://stdout Copy to buffer from CLI: • MacOS: echo $res | pbcopy • Linux: echo $res | xclip … • Windows: 
  • 45. Magento The more sophisticated things #Joined array turns out to be more flexible than HEREDOC: function generateStuff ($FIRST, $SECOND, $SECOND_CAMELCASED, $needsSomething = true) { $tmpl = array(); $tmpl[] = " ${$FIRST}Counts = array();"; $tmpl[] = " while ($row = $stmt->fetchObject()) {"; $tmpl[] = " ${$FIRST}Counts[(int) $row->{$SECOND}_id] = (int) $row- >num_{$FIRST}s;"; $tmpl[] = " }"; $tmpl[] = " "; if($needsSomething) { $tmpl[] = " foreach(${$SECOND}s as ${$SECOND}) {"; $tmpl[] = " if(isset (${$FIRST}Counts[${$SECOND}- >getId()])) {"; $tmpl[] = " ${$SECOND}- >setUsercount(${$FIRST}Counts[${$SECOND}->getId()]);"; $tmpl[] = " }"; $tmpl[] = " }"; $tmpl[] = ""; } $tmpl = join("n", $tmpl); return $tmpl; }
  • 46. Magento Real life: tagged keys in cache Goal: • Resultset of a method could be cached • Resultset is dependent on other resultsets validity • If dependent resultset becomes invalid – invalidate only needed keys • Perform application-wide substitutions like currently logged in user and etc • Make adding and removing cache really easy Bad things • Require complex code to maintain • Hard to read
  • 47. Magento Solution  Java EhCache framework – http://ehcache.org/  @Cacheable & @TriggersRemove with tagging- specific features  Generate code for proxy class  Substitute original class within inversion of control container  Call the same method without any API change  Turn off caching when needed
  • 50. Magento Real life: add security restrictions  Goal: • Protect methods of service from unauthorized access • Have access granularity to actions of controller • Limit access for modifying particular entities • Make it easy  Solutions: • Symfony2 – JmsSecurityExtraBundle – http://bit.ly/sX0hN6 • DiExtraBundle – autowiring stuff – http://bit.ly/t7pP89 • AopBundle – intercept method calls – http://bit.ly/vFqWSD
  • 52. Magento Fast forms & XML * Doctrine OXM: http://github.com/doctrine/oxm
  • 54. Magento Thank you • http://twitter.com/nf_x • http://ua.linkedin.com/smertin