The document provides an overview of Twig, a templating language for PHP. It discusses some key benefits of Twig over plain PHP templates, including terse syntax, automatic HTML escaping, and ability to create custom templating extensions. The document also covers various Twig features like conditionals, loops, macros, template inheritance with blocks, and extending Twig with filters, functions, globals, tests, operators, token parsers and node visitors.
This document appears to be contact information for two individuals, Prof. Neeraj Bhargava and Abhishek Kumar, who work in the Department of Computer Science at the School of Engineering & System Sciences at MDS University in Ajmer, Rajasthan, India.
The document discusses three address code, an intermediate representation in compilers that uses at most three operands and one operator per instruction. It explains how three address code works, different implementations like quadruples and triples, and provides an example of converting the expression ((a+b)-((a+b)*(a-b)))+((a+b)*(a-b))) to three address code. Three address code simplifies intermediate code generation and machine code conversion in compilers.
This C program implements a deque (double-ended queue) using a linked list. The deque supports the basic operations of initialization, checking for emptiness, adding/removing elements from the front/rear, and printing the elements. Functions are defined to initialize the deque, check if it is empty, add elements to the front/rear, remove elements from the front/rear, and print the elements. These functions are used in main() to demonstrate adding/removing elements from both ends and printing the deque.
The document discusses improving code quality through object calisthenics and readability tips. Object calisthenics are a set of simple exercises to help internalize principles of object-oriented design, like having only one level of indentation per method. Readability tips include writing code that minimizes the time for others to understand it, using single line if statements for simple operations, and returning early from functions. Native PHP functions are also preferable for performance over pure PHP implementations.
This document provides an overview of objects, testing, and responsibility in software development. It discusses object-oriented programming concepts like abstraction, encapsulation, inheritance and polymorphism. It emphasizes the importance of testing and gives examples of good and bad testing practices. Responsibility is discussed in the context of objects having well-defined responsibilities and developers being responsible for writing clean, well-tested code.
Wordpress Plugin Development Practicesserversideup
油
These slides are from a presentation given by Dan Pastori of 521 Dimensions that were presented at Milwaukee Wordcamp in June of 2012. These slides represent the best practices when it comes to developing a Wordpress Plugin.
Twig is a template engine for PHP that is described as flexible, fast, and secure. Some key features of Twig include being concise yet powerful, with a template-oriented syntax. It aims to be easy to learn yet extensible. Twig provides features like inheritance, blocks, automatic escaping, and inclusion. It also focuses on being secure, with descriptive error messages and the ability to sandbox templates.
Symfony2 and MongoDB - MidwestPHP 2013 Pablo Godel
油
In this talk we will see how to use MongoDB in Symfony2 projects to speed up the development of web applications. We will give an introduction of MongoDB as a NoSQL database server and look at the options on how to work with it from Symfony2 and PHP applications.
Part 3 of a bespoke in-company training. Complete set of slides under:
Part 1: /VasilyKartashov/effective-php-part-1
Part 2: /VasilyKartashov/effective-php-part-2
Part 3: /VasilyKartashov/effective-php-part-3
Part 4: /VasilyKartashov/effective-php-part-4
Part 5: /VasilyKartashov/effective-php-part-5
Part 6: /VasilyKartashov/effective-php-part-6
More about the author: http://notes.kartashov.com/about/
Twig is a template engine for PHP. It parses templates into tags, prints, and blocks. The lexer tokenizes templates into tokens, and the parser converts tokens into an AST. The compiler generates PHP code from the AST. Twig supports tags like for loops and if/else, macros, and internationalization. It can be extended with custom tags, filters, functions. Security features include escaping, sandboxing and permissions. Templates can access objects and be rendered without controllers.
Building maintainable javascript applicationsequisodie
油
In this presentation I share some tips about how to improve the quality and readability of JavaScript code, more specifically:
- Object Oriented JavaScript (comparing JS with Java)
- Bad practices
- Good practices
- Guidelines
- Recommended books
Dependency injection is a powerful technique allowing different parts of a system to collaborate with each other. Injection is the passing of a dependency (such as a service or database connection) to an object that would use it. This way, the object need not change because the outside service changed. This often also allows the object to be more easily tested by injecting a mock or stub service as the dependency.
The document proposes an IT infrastructure for Shiv LLC, a company with locations in Los Angeles, Dallas, and Houston. It recommends implementing an Active Directory domain to enable communication and file sharing across the three locations. A centralized file server would store common files and applications. Each location would have its own local area network, connected to the other sites and to the internet via VPN. Firewalls, antivirus software, and regular backups would help secure the network and protect company data. The design allows for future growth and expansion as the company scales up.
The document summarizes Karsten Dambekalns' presentation on persistence in FLOW3 using Doctrine 2. It discusses [1] how Doctrine 2 is seamlessly integrated and provides object persistence in FLOW3, [2] the basic usage of repositories to perform CRUD operations, and [3] advanced querying capabilities using both the Query Object Mapper and DQL. It also covers modeling associations, schema management through migrations, and checking the migration status.
If you have a problem, if no one else can help... and if you can find them, m...bitcoder
油
Ever had a problem?
No one could help you?
Please call the BASH Team!
This presentation starts with some preliminary thoughts about software integration.
Shell scripting means knowing your system and the applications you have available that can do the dirty stuff for you.
BASH is all about gluing... so what are the ways we can use to control resources and integrate software through scripting?
Some set of "advanced" features of BASH are explained and I'm sure you'll find them very handy to enhance your scripts. The BASH recipes can be used for common daily tasks of end users or administrators.
"Hacking" web sites can also be done using BASH and some command line tools. We'll talk a bit about it.
Learn also with real examples explained, namely:
- fetch music streams from web URL's to disk, from a popular Portuguese radio station
- emulate a user/replicate online banking tasks and extract values automatically, with a real bank example (by means of "reverse engineering" web pages)
- send SMS from command line, using a mobile operator's site (by means of "reverse engineering" web pages)
This is not intended to be a BASH tutorial for beginners, neither a simple plain tutorial. It's more a kind of BASH "hacking" guide.
The document discusses several software design patterns and concepts used in Zend Framework 3 including singleton, dependency injection, factory, data mapper, caching, and logging. It provides definitions and examples of how each pattern addresses issues like high cohesion, loose coupling, and testability. Key benefits are outlined such as reusability, reduced dependencies, and more readable code.
This document summarizes a presentation on metaprogramming in Ruby. Metaprogramming is writing code that writes code. It allows generating methods at runtime, extending core classes, and keeping code DRY. Examples given include how ActiveRecord reads the database schema at runtime to generate model methods, and defining methods dynamically using define_method. The document also discusses Ruby's object model and how everything, including classes, are objects that can be introspected and modified.
Mojolicious is a real-time web framework for Perl that provides a simplified single file mode through Mojolicious::Lite. It has a clean, portable, object oriented API without hidden magic. It supports HTTP, WebSockets, TLS, IPv6 and more. Templates can use embedded Perl and are automatically rendered. Helpers, sessions, routing and testing utilities are built in. The generator can create new app structures and components.
Lithium: The Framework for People Who Hate FrameworksNate Abele
油
This is the presentation was given at ConFoo on March 11th by Nate Abele and Jo谷l Perras, and is an introduction to the architectural problems with other frameworks that Lithium was designed to address, and how it addresses them. It also introduces programming paradigms like functional and aspect-oriented programming which address issues that OOP doesn't account for.
Finally, the talk provides a quick overview of the innovative and unparalleled features that Lithium provides, including the data layer, which supports both relational and non-relational databases.
Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...swentel
油
Session given at DrupalCamp Baltics 2013. Overview of the configuration management system in Drupal 8. Covers the api, config entities, context system.
The document discusses hashes in Perl programming. It explains that hashes allow the storage of key-value pairs and do not maintain order. It provides examples of creating a hash, accessing values using keys, and iterating through keys and values. It also discusses using hashes to store the genetic code and amino acid translations.
- The document discusses object-oriented programming concepts in PHP including classes, objects, encapsulation, inheritance, and polymorphism.
- It provides examples of defining classes with properties and methods, and using access specifiers like public, private, and protected.
- Constructors and destructors are explained, as well as how to instantiate objects and use objects in arrays or pass them as references to functions.
Make Apache bend to your will! We'll look at two ways to have fun with apache and mod_perl.
First, we'll see how to write a simple Apache2 module that acts as an output filter (munging text in certain pages) according to parameters from your Apache configuration.
Next, we'll look at a more drastic modification - changing Apache::Registry itself to add some new behaviors, such as sending an email when a perl script dies.
This topic is based on modules developed at the Sol Genomics Network, http://sgn.cornell.edu. Attendees will be encouraged to adapt these techniques for their own nefarious purposes.
This document discusses dependency injection in CakePHP. It begins by explaining what dependency injection is, then discusses how it can be implemented simply with constructors. However, real-world projects are more complicated, requiring additional patterns like factories, locators, and containers. The document notes that CakePHP currently does not help with dependency injection in application logic, but this will change in version 4.2 with the introduction of an experimental container system and injected application services. The container will allow registering and resolving services, and services will be automatically injected into controllers and actions. While still experimental, the goal is to stabilize the container approach in future versions through testing and feedback.
This document discusses upcoming releases and changes in CakePHP.
It outlines support timelines for CakePHP 2.X, 3.X and the upcoming 4.0.0 release. Version 4.0.0 is aimed to make CakePHP safer and more helpful. The document provides examples of changes in 4.0.0 like stricter type declarations, safer method calls, leveraging static analysis and consistent null handling to improve safety. It also discusses improved error messages and pages. An upgrade tool is introduced to help upgrade applications and plugins to new versions. Next steps mentioned include adding PSR-11 support and continued focus on developer experience for 4.1.
This document provides an overview of objects, testing, and responsibility in software development. It discusses object-oriented programming concepts like abstraction, encapsulation, inheritance and polymorphism. It emphasizes the importance of testing and gives examples of good and bad testing practices. Responsibility is discussed in the context of objects having well-defined responsibilities and developers being responsible for writing clean, well-tested code.
Wordpress Plugin Development Practicesserversideup
油
These slides are from a presentation given by Dan Pastori of 521 Dimensions that were presented at Milwaukee Wordcamp in June of 2012. These slides represent the best practices when it comes to developing a Wordpress Plugin.
Twig is a template engine for PHP that is described as flexible, fast, and secure. Some key features of Twig include being concise yet powerful, with a template-oriented syntax. It aims to be easy to learn yet extensible. Twig provides features like inheritance, blocks, automatic escaping, and inclusion. It also focuses on being secure, with descriptive error messages and the ability to sandbox templates.
Symfony2 and MongoDB - MidwestPHP 2013 Pablo Godel
油
In this talk we will see how to use MongoDB in Symfony2 projects to speed up the development of web applications. We will give an introduction of MongoDB as a NoSQL database server and look at the options on how to work with it from Symfony2 and PHP applications.
Part 3 of a bespoke in-company training. Complete set of slides under:
Part 1: /VasilyKartashov/effective-php-part-1
Part 2: /VasilyKartashov/effective-php-part-2
Part 3: /VasilyKartashov/effective-php-part-3
Part 4: /VasilyKartashov/effective-php-part-4
Part 5: /VasilyKartashov/effective-php-part-5
Part 6: /VasilyKartashov/effective-php-part-6
More about the author: http://notes.kartashov.com/about/
Twig is a template engine for PHP. It parses templates into tags, prints, and blocks. The lexer tokenizes templates into tokens, and the parser converts tokens into an AST. The compiler generates PHP code from the AST. Twig supports tags like for loops and if/else, macros, and internationalization. It can be extended with custom tags, filters, functions. Security features include escaping, sandboxing and permissions. Templates can access objects and be rendered without controllers.
Building maintainable javascript applicationsequisodie
油
In this presentation I share some tips about how to improve the quality and readability of JavaScript code, more specifically:
- Object Oriented JavaScript (comparing JS with Java)
- Bad practices
- Good practices
- Guidelines
- Recommended books
Dependency injection is a powerful technique allowing different parts of a system to collaborate with each other. Injection is the passing of a dependency (such as a service or database connection) to an object that would use it. This way, the object need not change because the outside service changed. This often also allows the object to be more easily tested by injecting a mock or stub service as the dependency.
The document proposes an IT infrastructure for Shiv LLC, a company with locations in Los Angeles, Dallas, and Houston. It recommends implementing an Active Directory domain to enable communication and file sharing across the three locations. A centralized file server would store common files and applications. Each location would have its own local area network, connected to the other sites and to the internet via VPN. Firewalls, antivirus software, and regular backups would help secure the network and protect company data. The design allows for future growth and expansion as the company scales up.
The document summarizes Karsten Dambekalns' presentation on persistence in FLOW3 using Doctrine 2. It discusses [1] how Doctrine 2 is seamlessly integrated and provides object persistence in FLOW3, [2] the basic usage of repositories to perform CRUD operations, and [3] advanced querying capabilities using both the Query Object Mapper and DQL. It also covers modeling associations, schema management through migrations, and checking the migration status.
If you have a problem, if no one else can help... and if you can find them, m...bitcoder
油
Ever had a problem?
No one could help you?
Please call the BASH Team!
This presentation starts with some preliminary thoughts about software integration.
Shell scripting means knowing your system and the applications you have available that can do the dirty stuff for you.
BASH is all about gluing... so what are the ways we can use to control resources and integrate software through scripting?
Some set of "advanced" features of BASH are explained and I'm sure you'll find them very handy to enhance your scripts. The BASH recipes can be used for common daily tasks of end users or administrators.
"Hacking" web sites can also be done using BASH and some command line tools. We'll talk a bit about it.
Learn also with real examples explained, namely:
- fetch music streams from web URL's to disk, from a popular Portuguese radio station
- emulate a user/replicate online banking tasks and extract values automatically, with a real bank example (by means of "reverse engineering" web pages)
- send SMS from command line, using a mobile operator's site (by means of "reverse engineering" web pages)
This is not intended to be a BASH tutorial for beginners, neither a simple plain tutorial. It's more a kind of BASH "hacking" guide.
The document discusses several software design patterns and concepts used in Zend Framework 3 including singleton, dependency injection, factory, data mapper, caching, and logging. It provides definitions and examples of how each pattern addresses issues like high cohesion, loose coupling, and testability. Key benefits are outlined such as reusability, reduced dependencies, and more readable code.
This document summarizes a presentation on metaprogramming in Ruby. Metaprogramming is writing code that writes code. It allows generating methods at runtime, extending core classes, and keeping code DRY. Examples given include how ActiveRecord reads the database schema at runtime to generate model methods, and defining methods dynamically using define_method. The document also discusses Ruby's object model and how everything, including classes, are objects that can be introspected and modified.
Mojolicious is a real-time web framework for Perl that provides a simplified single file mode through Mojolicious::Lite. It has a clean, portable, object oriented API without hidden magic. It supports HTTP, WebSockets, TLS, IPv6 and more. Templates can use embedded Perl and are automatically rendered. Helpers, sessions, routing and testing utilities are built in. The generator can create new app structures and components.
Lithium: The Framework for People Who Hate FrameworksNate Abele
油
This is the presentation was given at ConFoo on March 11th by Nate Abele and Jo谷l Perras, and is an introduction to the architectural problems with other frameworks that Lithium was designed to address, and how it addresses them. It also introduces programming paradigms like functional and aspect-oriented programming which address issues that OOP doesn't account for.
Finally, the talk provides a quick overview of the innovative and unparalleled features that Lithium provides, including the data layer, which supports both relational and non-relational databases.
Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...swentel
油
Session given at DrupalCamp Baltics 2013. Overview of the configuration management system in Drupal 8. Covers the api, config entities, context system.
The document discusses hashes in Perl programming. It explains that hashes allow the storage of key-value pairs and do not maintain order. It provides examples of creating a hash, accessing values using keys, and iterating through keys and values. It also discusses using hashes to store the genetic code and amino acid translations.
- The document discusses object-oriented programming concepts in PHP including classes, objects, encapsulation, inheritance, and polymorphism.
- It provides examples of defining classes with properties and methods, and using access specifiers like public, private, and protected.
- Constructors and destructors are explained, as well as how to instantiate objects and use objects in arrays or pass them as references to functions.
Make Apache bend to your will! We'll look at two ways to have fun with apache and mod_perl.
First, we'll see how to write a simple Apache2 module that acts as an output filter (munging text in certain pages) according to parameters from your Apache configuration.
Next, we'll look at a more drastic modification - changing Apache::Registry itself to add some new behaviors, such as sending an email when a perl script dies.
This topic is based on modules developed at the Sol Genomics Network, http://sgn.cornell.edu. Attendees will be encouraged to adapt these techniques for their own nefarious purposes.
This document discusses dependency injection in CakePHP. It begins by explaining what dependency injection is, then discusses how it can be implemented simply with constructors. However, real-world projects are more complicated, requiring additional patterns like factories, locators, and containers. The document notes that CakePHP currently does not help with dependency injection in application logic, but this will change in version 4.2 with the introduction of an experimental container system and injected application services. The container will allow registering and resolving services, and services will be automatically injected into controllers and actions. While still experimental, the goal is to stabilize the container approach in future versions through testing and feedback.
This document discusses upcoming releases and changes in CakePHP.
It outlines support timelines for CakePHP 2.X, 3.X and the upcoming 4.0.0 release. Version 4.0.0 is aimed to make CakePHP safer and more helpful. The document provides examples of changes in 4.0.0 like stricter type declarations, safer method calls, leveraging static analysis and consistent null handling to improve safety. It also discusses improved error messages and pages. An upgrade tool is introduced to help upgrade applications and plugins to new versions. Next steps mentioned include adding PSR-11 support and continued focus on developer experience for 4.1.
The document discusses the past, present, and future of CakePHP versioning. It notes challenges with past major upgrades and lessons learned. It outlines improvements in the 3.2-3.4 range like stronger typing and middleware usage. Future plans include new middleware types in 3.5, deprecation warnings in 3.6, and a major 4.0 release removing PHP5 support. Long term support periods are proposed for 2.x, 3.6 and beyond to ensure backwards compatibility while improving the framework.
The document discusses the future of HTTP support in CakePHP. It outlines plans to adopt the PSR-7 standard for HTTP message interfaces. PSR-7 support will be introduced as an opt-in middleware stack in version 3.3, and will become the default stack in 3.4. The new stack will provide improved request and response objects, and support for middleware. The transition is designed to be backwards compatible, with deprecation warnings before removing legacy features in CakePHP 4.0.
This document provides a summary of new features in CakePHP 3.0 including:
- Frequent releases with bugfixes every 2-4 weeks and support for PHP 5.4 and above.
- Adoption of PSR standards and improvements to internationalization, routing, resource routing, collections, ORM, and entities.
- Key changes include standalone components, improved localization support, routing scopes and prefixes, resource routing, immutable and pipeline-friendly collections, active record and datamapper ORM patterns, and value objects.
- Many features can also be used independently of CakePHP.
The document summarizes updates and new features for CakePHP version 3.0 and beyond. It discusses the large number of breaking changes in 3.0.0, challenges with upgrading, and areas that went well like community involvement and documentation. It outlines the future release schedule and previews some new features including mailers, console improvements, ORM enhancements, ElasticSearch integration, and PSR-7 support. It notes efforts to maintain backwards compatibility within the 3.x series and questions about supporting older PHP versions. The document encourages community involvement to help with upcoming CakePHP releases.
The document discusses best practices for open source projects, including being respectful to community members, having transparent processes, writing documentation that is easy to maintain and use, following semantic versioning, and releasing in a simple way. It also notes the importance of empowering others, setting a good example, and making mistakes to learn and improve.
This document discusses best practices for open source projects and frameworks, including being respectful of all community members, having high-quality documentation, following semantic versioning, being transparent about releases and security fixes, and providing migration guides for breaking changes. It also recommends having opinions but flexibility in code generation and conventions, future-proofing APIs, and learning from mistakes in an open and rewarding process.
Performance and optimization CakeFest 2014markstory
油
This document provides guidelines and techniques for profiling and optimizing performance. It recommends measuring performance metrics, prioritizing front-end optimizations like reducing file sizes and HTTP requests before backend optimizations, and optimizing code last after other techniques. Specific techniques discussed include minifying assets, compressing images, adding caching, using developer tools to identify issues, and PHP profiling tools like XHProf and XDebug.
The document summarizes the road to CakePHP 3.0, including that the first commit was in May 2012, there have been over 6000 commits from 20 contributors, and over 1500 book commits from 51 contributors. It highlights some of the key changes in CakePHP 3.0, such as using PHP5.4 and Composer, a new app skeleton, simpler configuration, improved ORM and router performance, and string templates. It also discusses plans for future beta releases and support through 3.x releases.
This document provides guidelines and techniques for profiling and optimizing performance. It discusses measuring performance using tools like Chrome Developer Tools, optimizing assets by minifying files and images, improving database queries with indexing and caching, and profiling code with tools like XHProf and the Chrome CPU profiler. The overall guidelines emphasized are to measure everything, start optimizations in the front-end, avoid unnecessary work, and optimize code last.
This document discusses the OWASP Top 10 security risks and provides examples and prevention methods for each. It covers injection flaws, broken authentication, XSS, insecure direct object references, security misconfiguration, sensitive data exposure, missing access control, CSRF, using vulnerable components, and unvalidated redirects. For each risk, it explains potential impacts, provides code examples to illustrate the issue, and recommends techniques to address the vulnerability like input validation, access control, encryption, and keeping software updated.
The document discusses lessons learned from the creator's experience leading the development of the CakePHP framework. It touches on topics like maintaining an open and respectful community, prioritizing documentation and easy upgrades, balancing conventions with flexibility, and embracing mistakes as opportunities for growth. The overall message is that building an open source framework comes with many challenges but can be rewarding.
The document discusses the top 10 security exploits as identified by the Open Web Application Security Project (OWASP). It covers the risks and prevention strategies for each exploit, including SQL injection, cross-site scripting (XSS), broken authentication and session management, insecure direct object references, cross-site request forgery (CSRF), security misconfiguration, insecure cryptographic storage, failure to restrict URL access, insufficient transport layer protection, and unvalidated redirects and forwards. Prevention strategies emphasized input validation, output encoding, access control, secure configuration, cryptographic best practices, and not trusting user-supplied redirect URLs.
Elasticsearch is a JSON document database that allows for powerful full-text search capabilities. It uses Lucene under the hood for indexing and search. Documents are stored in indexes and types which are analogous to tables in a relational database. Documents can be created, read, updated, and deleted via a RESTful API. Searches can be performed across multiple indexes and types. Elasticsearch offers advanced search features like facets, highlighting, and custom analyzers. Mappings allow for customization of how documents are indexed. Shards and replicas improve performance and availability. Multi-tenancy can be achieved through separate indexes or filters.
This document discusses new features in CakePHP version 2.2 related to view blocks, JSON and XML views, improved hashing performance, date/time utilities, and scoped logging. It provides examples of using view blocks to keep HTML DRY, creating JSON views, benchmarking hash performance improvements over sets, using the new CakeTime and CakeNumber utilities, and attaching loggers with scopes to filter log messages.
The document discusses continuous integration, which aims to improve software quality and reduce delivery time by implementing quality control throughout development rather than after completion. It does this through practices like version control, local sandboxes, automated testing across staged environments. Continuous integration provides benefits like more frequent commits with confidence, visibility, and faster feedback through automated bots that behave predictably and consistently by always testing, building, and deploying code. Jenkins is mentioned as an easy to use continuous integration server with a large community and plugins.
CakePHP 2.0 has been re-factored and rebuilt with many internal and external API changes. It uses native PHP5 features, updated conventions for class and file names, and a new loader. Exceptions replace the old error handling. Collections unify how helpers, components, behaviors and tasks are loaded and used. The console, request/response, sessions, authentication, email, and testing have all been improved for better performance and extensibility. Benchmarks show CakePHP 2.0 has significantly better performance than 1.3.11.
2. ABOUT ME
Team lead at FreshBooks
Lead Developer of CakePHP
Contributor to Twig
Saturday, 3 November, 12
3. WHAT IS IT
Templating language for PHP.
Uses syntax and ideas from jinja2.
Flexible and extensible at every layer.
Saturday, 3 November, 12
4. BUT PHP IS A
TEMPLATING
LANGUAGE DUMMY
Saturday, 3 November, 12
5. PHP SUCKS FOR TEMPLATING
// In Plain PHP
<?php echo $var; ?> (XSS you lose)
<?php echo htmlspecialchars($var, ENT_QUOTES, UTF-8); ?>
<?php echo h($var); ?> (sugar for htmlentities)
// In Twig - autoescaping enabled
{{ var }}
Saturday, 3 November, 12
6. BENEFITS OF TWIG
Terse syntax, and sugar.
Automatic HTML escaping.
Sandbox mode, which enables user editable templates.
Ability to create custom DSLs using application tags, operators
and functions.
Saturday, 3 November, 12
15. IMPORTING MACROS
// import all the macros
{% import /import/formatting.twig as formatting %}
{{ formatting.username(user) }}
// import one macro
{% from /import/formatting.twig import username %}
{{ username(user) }}
// import one & alias it.
{% from /import/formatting.twig import username as un %}
{{ un(user) }}
Saturday, 3 November, 12
16. INHERITANCE & BLOCKS
Extending views & blocks work hand in hand.
Blocks are like slots or holes in a template, that the child can 鍖ll.
Blocks can be used out of order, which is pretty sweet.
Blocks can be imported from other templates, similar to traits.
Saturday, 3 November, 12
17. INHERITANCE
{# layout/base.twig #}
Company X - Official Email template
{% block content Super important %}
Copyright 2012
Saturday, 3 November, 12
18. INHERITANCE
{# email/winner.twig #}
{% extend /layout/base.twig %}
{% block content %}
To whom it may concern,
You win!
{% endblock %}
Saturday, 3 November, 12
19. INHERITANCE
{# email/winner.twig #}
{% extend /layout/base.twig %}
{% block content %}
To whom it may concern,
{{ parent() }} You win!
{% endblock %}
Saturday, 3 November, 12
20. INHERITANCE TIPS
Dont use {% block %} inside a loop. It doesnt do what you
want.
You can use {{ block(name) }} to dynamically call blocks.
Saturday, 3 November, 12
22. EXTENDING TWIG
Twig can be extended in several ways.
Filters, Functions, Globals, Tests, Operators, TokenParsers,
NodeVisitors.
You should use extensions to package up your enhancements.
Saturday, 3 November, 12
24. LOADING EXTENSIONS
$loader = new Twig_Loader_FileSystem(APP . /templates);
$twig = new Twig_Environment($loader, $options);
$twig->addExtension(new App_Extension_Url());
Saturday, 3 November, 12
25. ENVIRONMENT FACTORY
class AppTwig {
static function loadTemplate($template, $options = array()) {
$loader = new Twig_Loader_FileSystem(APP . /templates);
$twig = new Twig_Environment($loader, $options);
$twig->addExtension(new App_Extension_Url());
// Load more extensions
return $twig->loadTemplate($template);
}
}
$template = AppTwig::loadTemplate(/users/profile.twig);
Saturday, 3 November, 12
26. EXTENSION EXAMPLE
<?php
class App_Extension_Url extends Twig_Extension {
public function getName() {
return app.url;
}
public function getFilters() {
return array(
name => new Twig_Filter_Method($this, formatName),
);
}
}
Saturday, 3 November, 12
27. GLOBALS
Can be used to expose application or framework objects.
Great for migrating an older codebase to use Twig.
E.g {{ html.link(...) }}
Saturday, 3 November, 12
28. FUNCTIONS
Global functions added to a template context.
Great for providing shortcuts to application features, like url
generation or built-in PHP functions.
Example {{ form_input(model, name) }}
Saturday, 3 November, 12
29. FILTERS
Filters are intended for simple formatting functions.
The 鍖ltered variable is the 鍖rst argument to the 鍖lter function.
Filters can have additional arguments as well.
Example: {{ invoice.amount|currency(CAD) }}
Saturday, 3 November, 12
30. TESTS
Allow you to implement custom conditional logic. In an
expressive manner with domain objects.
Value being compared is supplied as the 鍖rst argument. Other
arguments follow.
{% if user is paying %}
{% if number is divisibleby(3) %}
Saturday, 3 November, 12
31. NODE VISITORS
Allows you to visit each node in the Abstract syntax tree.
Applied before template is compiled.
Commonly used for optimizing the AST, or applying
transformations to, or reading data from nodes in the tree.
Saturday, 3 November, 12
40. TOKEN PARSERS
Used to implement custom tags or DSL features.
The most complex feature to add.
Each tag is composed of two parts:
TokenParser - parses the tag and validates its syntax.
Node - Added to the AST and compiles the PHP code used
in templates.
Saturday, 3 November, 12
41. TAG EXAMPLE
{% debug %}
{% debug my_var %}
{% debug 2 > 1 %}
Saturday, 3 November, 12
42. TOKEN PARSER
class App_TokenParser_Debug extends Twig_TokenParser {
public function parse(Twig_Token $token) {
$line = $token->getLine();
$expr = null;
if (!$this->parser->getStream()->test(Twig_Token::BLOCK_END_TYPE)) {
$expr = $this->parser->getExpressionParser->parseExpression();
}
$this->parse->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
return new App_Node_Debug($expr, $line, $this->getTag());
}
}
Saturday, 3 November, 12
43. NODE COMPILER
class App_Node_Debug extends Twig_Node {
public function __construct(Twig_Node_Expression $ex, $line, $tag) {
parent::__construct(array(expr => $ex), $line, $tag);
}
public function compile(Twig_Compiler $compiler) {
$compiler->write(if ($this->env->isDebug()) {);
if ($this->getNode(expr) === null) {
// Print all vars.
} else {
$compiler->write(var_dump()
->subcompile($this->getNode(expr))
->raw(););
}
$compiler->write(});
}
}
Saturday, 3 November, 12
44. OPERATORS
Allow you to add additional boolean operators.
Ive never used this feature.
Saturday, 3 November, 12
46. TWIG IN PRODUCTION
FreshBooks (the app, not the website).
520+ templates.
Twig templates are used for almost all HTML & E-mail content.
Saturday, 3 November, 12
57. TWIG C EXTENSION
You can also install ext/twig.
This pushes the most frequently used method
Twig_Template::getAttribute() into C which increases
performance considerably.
The C extension is in the Twig repository.
Saturday, 3 November, 12