PHPLondon: Agavi (2008-08-07)

65
Scale Your Development with the Agavi Framework

description

A presentation on the Agavi framework I gave at the PHPLondon user group's August meetup at Theodore Bullfrog's, London, UK.

Transcript of PHPLondon: Agavi (2008-08-07)

Page 1: PHPLondon: Agavi (2008-08-07)

Scale Your Developmentwith the Agavi Framework

Page 2: PHPLondon: Agavi (2008-08-07)

Many, many thanks to Simon Thulbourn.He saved this day.

Page 3: PHPLondon: Agavi (2008-08-07)

+ =

This is what happened...

Page 4: PHPLondon: Agavi (2008-08-07)

David Zülke

Page 5: PHPLondon: Agavi (2008-08-07)

David Zuelke

Page 6: PHPLondon: Agavi (2008-08-07)
Page 7: PHPLondon: Agavi (2008-08-07)

But worry not, I come in peace.We’re all friends now.

Page 8: PHPLondon: Agavi (2008-08-07)

(just don’t mention the war!)

Page 9: PHPLondon: Agavi (2008-08-07)

• Bitextender GmbH, based in Munich.de

• We’ve been doing development, consulting and training for 5+ years.

• Team of 7.

• The company behind Agavi, backing and developing it.

Page 10: PHPLondon: Agavi (2008-08-07)

But let’s move on to the non-boring stuff, shall we?

Page 11: PHPLondon: Agavi (2008-08-07)

FrameworksAnd why using them is a fabulous idea.

Page 12: PHPLondon: Agavi (2008-08-07)

Good Reasons

TCO is a lot lower than when rolling your own.

An open solution means there (hopefully) is a pool of talent to hire from.

There are experts in case your brightest developer is hit by a bus.

A community effort means the framework is put through its paces by many, not few.

Projects with proper momentum are unlikely to disappear overnight.

It’s more convenient too!

Page 13: PHPLondon: Agavi (2008-08-07)

Common Concerns

My developers would have to learn a new system.

True, but so would all new employees. It’ll pay off.

What if the project bites the dust tomorrow?

Then you need to maintain it yourself. That’s still not any different from what‘d be if you had your own.

They all suck, we need to use it to control a submarine.

Pick the one that works best and customize it.

Page 14: PHPLondon: Agavi (2008-08-07)

MVCAnd how it’s (not) working for web applications.

Page 15: PHPLondon: Agavi (2008-08-07)

Model

View

Controller

?

??

Page 16: PHPLondon: Agavi (2008-08-07)

Speaking of MVC...Of Criminal, Crazy, Heckling False Advertisers.

Page 17: PHPLondon: Agavi (2008-08-07)

Mike, the “Crazy Guy”

Was at the PHPLondon conference in February.

Heckled speakers and called them criminals.

Except he didn’t. It’s all lies misunderstandings.

“I don’t want to call anyone a criminal”.

Page 18: PHPLondon: Agavi (2008-08-07)

He was complaining about the “false advertising” that many frameworks do.

Page 19: PHPLondon: Agavi (2008-08-07)

And he had, and still has, a point.

Page 20: PHPLondon: Agavi (2008-08-07)

The Problem

Quick results are more important than sustainability.

Potential of framework to guide users is not leveraged.

Users are locked into the vendor’s way of doing things:

If you want RSS, your URLs must end on “.rss”

Our HTML helpers only work with PHP templates.

What, you don‘t like ActiveRecord?

Page 21: PHPLondon: Agavi (2008-08-07)

The Consequences

Simple changes are just as expensive as (or more expensive than) without a framework.

Developers end up hacking around weaknesses or assumptions in the framework that lead to bugs and maintenance nightmares.

The framework does not achieve its most fundamental mission: keeping your software fit for future demands.

In the end, it does not scale in any regard.

Page 22: PHPLondon: Agavi (2008-08-07)

From Mojavi to AgaviA brief history lesson.

Page 23: PHPLondon: Agavi (2008-08-07)

Mojavi 1, 2 and 3 were developed by Sean Kerr.

Development wasn’t open and transparent, despite the license (and awesomeness!), and died eventually.

Mojavi 3 was forked by some guys from Keller, Texas, and given the name Agavi in 2005.

Because Agave plants grow in the Mojave desert.

Since late 2005, Agavi is maintained by Bitextender.

symfony is also based on Mojavi 3.

Page 24: PHPLondon: Agavi (2008-08-07)

AgaviKey Features and Differences.

Page 25: PHPLondon: Agavi (2008-08-07)

No Assumptions

Being PHP based, it works best for websites and other HTTP-based stuff, but you can use it to write any app.

No requirements for specific template engines, DBMSes, ORMs, client side JS libraries etc.

Abstraction of HTTP request method verbs, output types, response implementations etc.

Form Handling is independent of libraries, template engines etc.

Page 26: PHPLondon: Agavi (2008-08-07)

Reuse Code

The right things are done in the right places, and the framework prevents common mistakes.

Exposing Actions of a web application through a SOAP web service API etc. can be done in minutes.

Want an RSS feed of your latest products? It’s just a new output type away.

Want to return JSON for Ajax features? Have it done when a JS framework sends the right request headers!

Page 27: PHPLondon: Agavi (2008-08-07)

Environments and Contexts

An Environment is bootstrapped for every box or developer. Could be “production”, or “dev-joecool” etc.

A Context represents a way of accessing the application, like “web”, “soap” or “console”.

Any configuration can be specific to one or more Environment(s) and/or Context(s).→ no more copying and overwriting of DB configs!

Page 28: PHPLondon: Agavi (2008-08-07)

Modules, Actions, Views etc

An Application has a number of Modules.

Each Module has Actions with corresponding Views and Templates, as well as various configuration files that control caching, validation and so on.

Actions, which can also be nested into folders, contain application logic, make calls to Models, and have one or more Views (“Error”, “Success”, “Input” etc.)

Views handle presentation, usually using Templates.

Page 29: PHPLondon: Agavi (2008-08-07)

Execution Containers

Every Action execution happens in an isolated Container.

Every container has it’s own request data, response, filters etc.

A normal execution is idempotent, i.e. does not affect the “outside world”.

Internal forwarding can be done by returning a new Container from a View.

Page 30: PHPLondon: Agavi (2008-08-07)

Filters

Global Filters or per-Action/Container filters.

Wrap the execution, and call the next Filter in the chain - like an Onion or a Russian Nested Doll.

Features like Security or Form Handling are implemented using Filters inside Agavi.

Flow can be redirected internally, response info can be modified etc; numerous possibilities.

Page 31: PHPLondon: Agavi (2008-08-07)

Layers and Layouts

A View can leave instructions on Templates to render; these are called Layers.

Each Layer has access to the output of the previous Layers, and can define Slots - Containers with Actions that are run before rendering, returning the content.

Layer and Slot definitions can be made in a configuration file; the result is a Layout.

All this can be done programmatically, as well.

Page 32: PHPLondon: Agavi (2008-08-07)

Routing

Used for matching URLs, SOAP method names.

Every route can have children.

Callbacks can control and modify behavior on matching or when generating URLs.

Routes can also set Output Types, force continuing of execution even though they matched, and much more.

Also very nice for refactoring existing applications.

Page 33: PHPLondon: Agavi (2008-08-07)

Form Handling

Form Population Filter makes form handling a breeze.

Can pre-populate forms using given values.

Re-populates a form when an error occurred.

Highlights erroneous fields and labels.

Can insert error messages into the document.

All without a single line of code in templates.

Page 34: PHPLondon: Agavi (2008-08-07)

Caching

Cache the entire execution of a request, or just parts.

Action-based, so a Slot that runs can be cached, too.

Output can be cached on a per-layer basis, so that the outer master template always runs even when cached.

Also caches cookies (with correct lifetime!), HTTP headers that were set etc.

Stampede Protection included as of Agavi 0.11.3.

Page 35: PHPLondon: Agavi (2008-08-07)

Validation

Validates not only request parameters, but also Files, Cookies and HTTP Headers.

Default settings mean you only have access to data you validated.

Drastically reduces the possibility for dev mistakes.

Validators can have dependencies (“only validate email if checkbox is on”), different severities, handle arrays, normalize values (e.g. make Unix TS from date value).

Page 36: PHPLondon: Agavi (2008-08-07)

Security

Security Filter is the internal mechanism to auto-check against credentials, authentication status etc.

Ships with plain and RBAC implementations, easily extensible.

Provided implementations work with the standard getCredentials() and isSecure() methods on Actions; any other behavior, additional authentication levels etc can be implemented in a custom Security Filter.

Page 37: PHPLondon: Agavi (2008-08-07)

Internationalization

Bundles the Unicode CLDR database with information about all locales of this world.

Functions for translating text, formatting and parsing dates, numbers and currency values, calendar and timezone operations, locale information (e.g. list of all countries in Japanese language etc.)

Parts of the functionality are ports of ICU, IBM’s Java/C library for globalization.

Page 38: PHPLondon: Agavi (2008-08-07)

ExamplesA.k.a. real code, the stuff everyone’s here for.

Page 39: PHPLondon: Agavi (2008-08-07)

An Action that lists productsclassProducts_LatestActionextendsAcmeStoreBaseProductsAction{publicfunctionexecute(AgaviRequestDataHolder$rd){//grabtheproductfindermodel.couldalsobedoctrineetc.$pfm=$this‐>getContext()‐>getModel('ProductFinder');//fetchalistoflatestproducts,let'sassumeit'sanarray$latestProducts=$pfm‐>fetchLatest()://assignitfortheView$this‐>setAttribute('products',$latestProducts);//gotoProducts_LatestSuccessViewreturn'Success';}}

Page 40: PHPLondon: Agavi (2008-08-07)

The corresponding View

classProducts_LatestSuccessViewextendsAcmeStoreBaseProductsView{publicfunctionexecuteHtml(AgaviRequestDataHolder$rd){//notmuchtodohere.let'sjustloadthedefaultlayout$this‐>setupHtml($rd);//andmaybesetapagetitle$this‐>setAttribute('title','LatestACMEProducts');}}

Page 41: PHPLondon: Agavi (2008-08-07)

The template, obviously...

<h2><?=$t['title']?></h2><dl><?phpforeach($t['products']as$p):?><dt><ahref="<?=$ro‐>gen('products.product.view',array('id'=>$p['id']))?>"><?=htmlspecialchars($p['name'])?></a></dt><dd><?=$tm‐>_c($p['price'])?></dd><?phpendforeach;?></dl>

Page 42: PHPLondon: Agavi (2008-08-07)

And routes to make it work

<routename="products"pattern="^/products"module="Products"><routename=".index"pattern="^$"action="Index"/><routename=".latest"pattern="^/latest$"action="Latest"/><routename=".product"pattern="^/(id:\d+)"action="Product"><routename=".view"pattern="^$"action=".View"/><routename=".gallery"pattern="^/gallery$"action=".Gallery"/></route></route>

Page 43: PHPLondon: Agavi (2008-08-07)

Now let’s add JSON!classShop_LatestProductsSuccessViewextendsAcmeStoreBaseShopView{publicfunctionexecuteHtml(AgaviRequestDataHolder$rd){/*...*/}publicfunctionexecuteJson(AgaviRequestDataHolder$rd){returnjson_encode($this‐>getAttribute('products'));}}

<routepattern="application/json"source="_SERVER[HTTP_ACCEPT]"stop="false"output_type="json"/><routename="products"pattern="^/products"module="Products"><!‐‐...‐‐></route>

<output_typename="html"><!‐‐...‐‐></output_type><output_typename="json"><parametername="http_headers"><parametername="Content‐Type">application/json</parameter></parameter></output_type>

Page 44: PHPLondon: Agavi (2008-08-07)

Or how about CSV?classShop_LatestProductsSuccessViewextendsAcmeStoreBaseShopView{publicfunctionexecuteHtml(AgaviRequestDataHolder$rd){/*...*/}publicfunctionexecuteJson(AgaviRequestDataHolder$rd){/*...*/}publicfunctionexecuteCsv(AgaviRequestDataHolder$rd){$csv=fopen('php://temp','r+');fputcsv($csv,$this‐>getAttribute('products'));rewind($fp);return$fp;}}

<routepattern="application/json"source="_SERVER[HTTP_ACCEPT]"stop="false"output_type="json"/><routepattern="/csv$"stop="false"cut="true"output_type="csv"/><routename="products"pattern="^/products"module="Products"><!‐‐...‐‐></route>

<output_typename="csv"><parametername="http_headers"><parametername="Content‐Type">text/csv</parameter></parameter></output_type>

Page 45: PHPLondon: Agavi (2008-08-07)

Form Handling

Page 46: PHPLondon: Agavi (2008-08-07)

Didn’t login as Chuck Norris!

Page 47: PHPLondon: Agavi (2008-08-07)

This is the Template file:

<formaction="<?phpecho$ro‐>gen('login');?>"method="post"id="foo"><dl><dt><labelfor="fe‐username"><?phpecho$tm‐>_('Username:','default.Login');?></label></dt><dd><inputtype="text"name="username"id="fe‐username"/></dd><dt><labelfor="fe‐password"><?phpecho$tm‐>_('Password:','default.Login');?></label></dt><dd><inputtype="password"name="password"id="fe‐password"/></dd><dt>&#160;</dt><dd><inputtype="checkbox"name="remember"id="fe‐remember"/><labelfor="fe‐remember"><?phpecho$tm‐>_('Logmeinautomatically.','default.Login');?></label></dd><dt>&#160;</dt><dd><inputtype="submit"value="<?phpecho$tm‐>_('Login','default.Login');?>"/></dd></dl></form>

Page 48: PHPLondon: Agavi (2008-08-07)

A Layout:<configurationcontext="web"><output_typesdefault="html"><output_typename="html"><renderersdefault="php"><renderername="php"class="AgaviPhpRenderer"><parametername="assigns"><parametername="routing">ro</parameter><parametername="request">rq</parameter><parametername="controller">ct</parameter><parametername="user">us</parameter><parametername="translation_manager">tm</parameter><parametername="request_data">rd</parameter></parameter></renderer></renderers><layoutsdefault="default"><layoutname="default"><layername="content"/><layername="decorator"><slotname="menu"module="Default"action="Menu"/><parametername="directory">%core.template_dir%</parameter><parametername="template">Master</parameter></layer></layout><layoutname="slot"><layername="content"/></layout></layouts><parametername="http_headers"><parametername="Content‐Type">text/html;charset=UTF‐8</parameter></parameter></output_type>

Page 49: PHPLondon: Agavi (2008-08-07)

The result:

Content LayerMenu Slot

Page 50: PHPLondon: Agavi (2008-08-07)

Nonsense Store Example

Page 51: PHPLondon: Agavi (2008-08-07)

Search Engine Spam Route:

<routename="search_engine_spam"pattern="^/products(/buy‐cheap‐{name:[\S\s]+}‐at‐agavi‐dot‐org)?/(id:\d+)$"module="Default"action="SearchEngineSpam"><defaultfor="name">/buy‐cheap‐{nonsense}‐at‐agavi‐dot‐org</default></route>

Page 52: PHPLondon: Agavi (2008-08-07)

The Caching rules:<cachingmethod="read"lifetime="2hours"><group>products</group><groupsource="request_parameter">name</group><groupsource="locale"/><view>Success</view><output_typename="html"><layername="content"/><template_variable>title</template_variable></output_type></caching>

Page 53: PHPLondon: Agavi (2008-08-07)

The Result:

Restored from cache

Page 54: PHPLondon: Agavi (2008-08-07)

ShowcaseProof that it’s just not all theory.

Page 56: PHPLondon: Agavi (2008-08-07)
Page 57: PHPLondon: Agavi (2008-08-07)
Page 60: PHPLondon: Agavi (2008-08-07)

The ChuckwallaA fat lizard from the Mojave desert (likely eats Agaves).

Was a prototype IRC bot application with an IRC Context and a Web interface.

IRC Routing implementation matched patterns against incoming messages.

<configurationcontext="irc"><!‐‐sosomeonecantype"!seenWombert"onIRC‐‐><routepattern="^!seen(username:\S+)$"action="LastSeen"/></configuration><configurationcontext="web"><!‐‐ontheweb,theURLis/seen/Wombert‐‐><routepattern="^/seen/(username:\S+)$"action="LastSeen"/></configuration>

Page 61: PHPLondon: Agavi (2008-08-07)

!e End

Page 62: PHPLondon: Agavi (2008-08-07)

Oh wait.

Page 63: PHPLondon: Agavi (2008-08-07)

One More Thing...Sunday, August 10, 2008:

- Tutorial manual at http://agavi.org/

- Agavi 1.0 beta 1 release!

Page 64: PHPLondon: Agavi (2008-08-07)

Questions?

Page 65: PHPLondon: Agavi (2008-08-07)

Thank You for Attending!

Shoot me an E-Mail: [email protected]

Slides are available online at http://talks.wombert.de/

http://agavi.org/ is the Agavi website

With Trac, Mailing Lists, PEAR Channel, Docs, ...

Join the Agavi IRC channel: #agavi on irc.freenode.net