php
Facebook Connect & Lithium
It seems to be a week full of different authentication methods here. Last I wrote about an LDAP Auth class adapter for Lithium that I wrote and now I'm going to go over using Facebook Connect with your Lithium project. As it turns out, it's also very easy and you can put everything you need within a library to keep things modular.
First things first, you'll need the Facebook Connect PHP SDK....It also wouldn't hurt to grab the JavaScript SDK. You'll probably end up using it. Continuing here with "step 1" you're going to alter that single PHP SDK file. I know, I know...Hang on and listen. When we use Lithium, we really like namespaces. I really pray for the day that all PHP libraries we pick up are namespaced, but that just isn't a reality yet. Fortunately the Facebook PHP SDK is very small. It's just one file with a few classes. Cool! So within that you'll put up at the very top: namespace facebook; Then you'll also need to put a slash (\) in three places. That's where you see (also up top) new Exception. Ensure those instantiations read new \Exception... Also where the FacebookApiException extends Exception, make that FacebookApiException extends \Exception. Alternatively, up top put: namespace \Exception; and you should also be ok. So you're really only talking about 2-4 small tiny itsy bitsy changes. So you can relax.
I'd put this into a library, right? Why not? So within your app\libraries folder make a "facebook" folder and rename that "facebook.php" file you just downloaded and make it "Facebook.php" because it's just not going to work otherwise. Ok? All good? At this point you have a "app\libraries\facebook\Facebook.php" file that has a few tiny tweaks to use namespaces. Cool? Ok, on with step 2.
Now let's setup our authentication in a pretty common fashion. We're talking about applying filters during the framework bootstrap process. Create a "config" folder and add a "bootstrap.php" file, so you have a "app\libraries\facebook\config\bootstrap.php" file. Within here is where you'll be applying some filters to setup the authentication for your site. Now, if you've done this before, it's going to be fairly familiar. I'm going to paste an example that will provide you Facebook Connect authorization only. It's different than what I'm using because I'm allowing people to login using accounts in my local database or with Facebook Connect. I also create a new user record upon logging in with Facebook Connect. That way users can create their local profiles just the same whether they registered with my site or used Facebook Connect bypassing a registration process. Your needs are most likely going to differ. If not, then maybe I can be convinced to wrap up a complete "User & Auth" library. Part of this is going to look exactly like the example they provide along with the FB PHP SDK. So, here we go:
use \lithium\storage\Session;
use \lithium\security\Auth;
use \lithium\action\Dispatcher;
use \lithium\action\Response;
use \facebook\Facebook;
use \facebook\FacebookApiException;
Session::config(array(
'default' => array('adapter' => 'Php')
));
Dispatcher::applyFilter('run', function($self, $params, $chain) {
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXXXX',
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
// Write the session
Session::write('fb_session', $session);
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
// This will come in handy later
Session::write('fb_logout_url', $facebook->getLogoutUrl());
// So set the Auth and pass along (in the session) the data from FB API
Auth::set('user', $me);
} else {
// Again, this will come in handy (unless you're using the JavaScript SDK)
Session::write('fb_login_url', $facebook->getLoginUrl());
// If no FB session, clear any local session we may have set
Auth::clear('user');
}
// Here's one way of locking out different actions based on login status.
$blacklist = array(
'pages/index',
'pages',
'recipes/create',
'dashboards/my_account'
);
$matches = in_array((string)$params['request']->url, $blacklist);
if($matches && !Auth::check('user')) {
return new Response(array('location' => '/users/login'));
}
return $chain->next($self, $params, $chain);
});
That's pretty much all you need (in the least) in your bootstrap process. Step three; we're going to place a Login and Logout button on the site. So we need to go to the view template of your choice (could be a user's controller's "login" action or could be elsewhere). Let's say it's the login action. Again, I recommend using the JavaScript SDK as well. I'm also going to assume you'd be using jQuery. Here's what our template might look like:
<?php $html->script('http://connect.facebook.net/en_US/all.js', array('inline' => false)); ?>
<script>
// initialize the library with the API key
FB.init({
appId : 'XXXXXXXXXXXXXXXX',
session : <?php echo json_encode(\lithium\storage\Session::read('fb_session')); ?>,
status : true,
cookie : true,
xfbml : true
});
// fetch the status on load
FB.getLoginStatus(handleSessionResponse);
$('#fb-connect-login').bind('click', function() {
FB.login(handleSessionResponse, {perms:'read_stream,publish_stream'});
});
$('#logout').bind('click', function() {
FB.logout(handleSessionResponse);
});
$('#disconnect').bind('click', function() {
FB.api({ method: 'Auth.revokeAuthorization' }, function(response) {
clearDisplay();
});
});
// no user, clear display
function clearDisplay() {
$('#user-info').hide('fast');
}
// handle a session response from any of the auth related calls
function handleSessionResponse(response) {
// if we dont have a session, just hide the user info
if (!response.session) {
clearDisplay();
return;
}
// if we have a session, query for the user's profile picture and name
FB.api(
{
method: 'fql.query',
query: 'SELECT first_name, last_name, pic_square FROM user WHERE uid=' + FB.getSession().uid
}, function(response) {
var user = response[0];
$('#user-info').html('<img src="' + user.pic_square + '">' + user.first_name + ' ' + user.last_name).show('fast');
});
}
</script>
<div>
<button id="login"></button>
<button id="logout"Logout></button>
<button id="disconnect"></button>
</div>
<div id="user-info" style="display: none;"></div>
That's just about all you'll need. \lithium\storage\Session::read('fb_session'); is going to hold all your session data from Facebook, but you'll probably want to be using the JavaScript SDK to actually do anything useful with that information since it will be limited. Don't forget that facebook limits the information that you are allowed to store locally within your database. You of course could also continue to use the Facebook PHP SDK all over your site to get this information.
If you don't want to use the JavaScript SDK, you'll have the login URL set in the session data from the filters you applied. You'll grab it from: \lithium\storage\Session::read('fb_login_url');
Of course you can get more complex...You can setup a bunch of ACL based on your needs and make users perform other final registration tasks or you can, like I did, combine this with your User's model and allow people to register and login without Facebook Connect or login with Facebook Connect as an alternative.
Lithium and LDAP Authentication
The Lithium framework for PHP 5.3+ is without a doubt my favorite framework (which is evident of course if you've read my blog). I was trying to get LDAP working with Symfony 1.4 and it's sfGuard plugin without a whole lot of luck. While I'm sure possible with more time (perhaps quite a bit), I gave up and just used Lithium because it was much much easier.
The adapters that Lithium uses for various classes are really key. If you wanted to make an adapter for the Auth class, you can really do so without much trouble. Take a look at the current Form adapter as an example. The bulk of what is really required for an adapter is a return from the check() method of false or true or some data. The data returned can then be cached into the user's session data. So basically just returning an array for example will set that data to the session and authenticate the user. Returning false, doesn't. Pretty easy!
Of course there's a lot that might need to go on from A to B but, understanding that, you can make an adapter for just about anything. So I got to cracking on the LDAP authentication. It's a little odd because we aren't logging into a database to then check some records to see if it matches what the user passed. LDAP kinda has all of it's authentication process within itself. You just basically need to pass to it the username and password and it'll return true or false. If it's true you've just bound a connection and can perform searches, etc.
I'm also working on a datasource for LDAP that will really dive into all the CRUD operations. However, for our basic authentication needs all we need is to be able to connect and retrieve the record for the account used to login. Simple.
You can grab the adapter from the Lithium lab. You'll put it under app/extensions/adapters/auth/Ldap.php. Then you'll want to use it pretty much like you'd use the Form adapter. Here's an example configuration:
use \lithium\storage\Session;
use \lithium\security\Auth;
// This is just for an example, you may run with a different session adapter (I keep mine in MongoDB for example)
Session::config(array(
'default' => array('adapter' => 'Php')
));
// Here's what you're after.
Auth::config(array(
'user' => array(
'adapter' => 'Ldap',
'server' => array(
'host' => 'ds1-sjc.entic.net',
'basedn' => 'o=entic.net',
'targetdn' => 'ou=People'
),
'fields' => array('uid'),
'session' => array(
'options' => array('name' => 'default')
)
)
));
What's the entic server? It's an actual LDAP service, a free one (well, paid services too). They let you store some records as one of their services, kinda like a giant Rolodex. I'm not really sure what the status of their project is, but I do know it was one way to test the LDAP for free. They actually have a few interesting services hosted "in the cloud" (and they are working on some more) so you may want to give them a look.
So what is going on here? Well, we have our host then we have the "basedn" which is typically o=something. It could also commonly be something like: dc=example,dc=com. Anyway...Then we have a "targetdn" which is basically just some more properties to tack on. I've left this key separate purely for organization reasons and who knows, you may need to alter the property for some reason independent of the basedn value. It could have been defined under the basedn. Your distinguished name requirements are going to vary based on LDAP server. Then you have the fields key which is yet again more properties to append to this long DN string that's required to login. In the case of this server it's "uid" and again this list of fields (which also exist in your login form) are pieced together to form the DN. Since we aren't going to present the user with a form to enter this long DN in...We just have the "uid" field exposed in our form. We could have shown some other fields maybe as a drop down option for a group. Again, this depends on your LDAP server's configuration. Now we also need to pass from the form a "password" field. It won't be appended to the DN, but it is of course passed along to login to the LDAP server. Here's what our login view template looks like:
<?=$this->form->create(); ?>
<?=$this->form->field('uid', array('label' => 'Username')); ?>
<?=$this->form->field('password', array('type' => 'password')); ?>
<?=$this->form->submit('Log in'); ?>
<?=$this->form->end(); ?>
I'm not going to go over in great detail how to setup Auth. I'm assuming you've used the Form adapter before. However, if you haven't ever setup auth before, you'll want to put that first Auth::config() part somewhere in your bootstrap process. You'll also need to protect methods in one of many manners. You might apply a filter to the Dispacther's run() method for example in your bootstrap right after the Auth::config() part. You're going to be calling Auth::check() to assist with whatever you do to protect parts of your app. So let's say you also have a controller (let's say UsersController which is quite common) that has a login() that looks something like this:
public function login() {
if($this->request->data) {
$user = Auth::check('user', $this->request);
}
if($user) {
// Might want to redirect somewhere else
$this->redirect('/pages/login_successful');
}
$data = $this->request->data;
return compact('data');
}
That's all there is to it! So now when you to go /users/login and use the form to login. What will then happen is upon a successful login (bind) to the LDAP server, the account record will be retrieved and set to the session data. So when you call Auth::check('user'); you will be returned with an array of data. You can use this to do whatever you need.
Pretty easy, right? This is strictly authentication, you aren't writing anything back to the LDAP server. That's what you'll need a datasource for and I promise to share that as well. It's currently under construction. Again, you can grab the LDAP Auth adapter here.
MongoDB Queries with Lithium: Part Three
This will probably be the last part of the series, unless I find some other type of query that may not be so obvious or that may be new in a future release of MongoDB. This will also probably contain the most obscure and complex examples.
Regex With $or
So, on with the good part first. You probably want to create some sort of search for content on your site, be it on the front end for visitors or the back for only admins...It's a common thing for a site and while it's always a good idea to use something like Lucene/Solr/Sphinx if you expect complex searches and lots of them...You can make a quick and dirty search with most databases such as MySQL via a FULL TEXT search. Well, MongoDB does one better and takes advantage of regex, which I posted about in the last article for this series...But this time we're going to use a new operator, the $or operator in conjunction with regex. This is new in MongoDB 1.5.3, so ensure that you at least that version.
What's the $or do? Well, the $or is important because if you make a query with regex or not and want to search multiple fields, you will have all results from both matches be returned. The $or keeps you from getting duplicate results. If you remember in part one we used $elemMatch when dealing with matching multiple conditions within objects. In this example, we aren't working with complex objects, we're just saying go find a regex pattern in the title or the body of some document. Then again, maybe you will need to also apply what you learned about $elemMatch in the previous article with something like this. Right, so get on with it.
// I'm making one call to MongoRegex() but you may need more.
$search_regex = new \MongoRegex('/'.$this->request->data['query'].'/i');
$conditions => array(
'public' => true,
'$or' => array(
array('title' => $search_regex),
array('directions' => $search_regex)
)
)
);
// Now you can put the query together (or define $conditions inline with the find() call)
$recipes = Recipe::find('all', array(
'fields' => array('title', 'url'),
'conditions' => $conditions
));
My head exploded at first, but it's quite easy to follow along with. A little tip? Reference the MongoDB documentation, make your queries in a console window and when you get back the results you want...Take the text you entered and print it out on your page where you're making the query. I just print out the guts between the parenthesis. Then with your $conditions array that you build, run json_encode() and also print that out on the screen. It's a good way to see how the array format is getting translated. It makes it a lot easier if you're not a human PHP->JSON translator. For complex objects it helps quite a bit.
So what does that do above? A little context. I have some recipes and I only want those marked as being true for the "public" field to be included in the results first and foremost. You may have similar needs with some sort of publish status. Then we're running a regex on the query string passed via POST, but we're running it on two fields. In my case I have the title for the recipe and then some directions. I may also want to search ingredients too. Of course ingredients is in an object for me, so hey where's that good ol' $elemMatch? Yay, more complexity.
Ok. So sticking with this...What is returned is exactly what you'd expect, any recipe that's publicly visible that has the query in the title or directions (case insensitive match).
Lithium's "like" array key will not work in this case for two fields. It will for one. So in other words:
// Will NOT work
$conditions = array(
'title' => array('like' => '/chicken/i'),
'directions' => array('like' => '/cook/i')
);
// WILL work, but won't give us what we're after
$conditions = array(
'title' => array('like' => '/chicken/i')
);
Again, keep in mind we also need to use the $or operator for a very important reason. We don't want duplicate records in our search results. How about the other operators and other conditions? Sure! You can apply the $nin and $ne and all the other operators too. Those are a little different though. So where we put in $or as if it was a field, we have to use $nin and $ne like the other article explained. Let me write it out again all glued together with the first example here.
$conditions => array(
'public' => true,
'$or' => array(
array('title' => $search_regex),
array('directions' => $search_regex)
)
),
'title' => array(
'$nin' => array('BBQ Chicken', 'More Chicken')
)
);
You can probably start to imagine how you would build an "advanced" search where you allowed the user to fill out a few different form fields that narrowed the search down. Ok, so let's glue together a query that combines a little of everything that we've gone over in all three articles. This will be as if a visitor came to the site, searched for recipes that were shared with a specific family (let's say their family), had "chicken" in the title/directions, and was not shared with the public. So only a private chicken recipe currently approved and shared with a specific family (group).
$conditions = array(
'public' => false,
'$or' => array(
array('title' => $search_regex),
array('directions' => $search_regex),
array('ingredients.ingredient' => $search_regex)
),
'title' => array(
'$nin' => array('More Chicken')
),
'families' => array(
'$elemMatch' => array(
'family_id' => '4c59d5ec7f8b9a6279000000',
'approved' => true
)
)
);
Confused? You will be, in this episode of MongoDB & Lithium...Right, so your queries can get rather complex. Hopefully you won't be confused after reading my article, but to be fair, that's complex even if you were to type it straight up in the console written as JSON. It's no different really, but don't think that you need to make a custom query with Lithium, your query can be represented as a PHP array which really helps you out with dynamic values.
The above query also looks at ingredients, which in my case are within an array. In a production situation I probably would build a more complex regular expression or possibly several. The query could end up even more complex based on what's posted along to my search method. This should really give you some ideas though. How does this impact the database? I'm not really sure. I haven't benchmarked this at all or anything.
The $type Operator
One last query for the road? Sure. This is a simple one and probably very obscure. MongoDB lets you query by data type. Wha?? Crazy right? I personally haven't found a real great use for this yet, but you never know. Here's an example:
$conditions = array(
'title' => array(
'$type' => 2
)
);
That will return every recipe where the title is a string. The $type operator accepts a list of numbers that are assigned to a BSON type. You can see the list of types on the MongoDB documentation page.
That's all for now, hope you enjoyed!
MongoDB Queries with Lithium: Part Two
Let's take a step back for part two. Let's ignore complex (or any) objects and here we're going to go over some more basic (and common) queries that you may need to make. No, there's not really much order to the queries I'm going to go over in this series, sorry. It started as more of an "I'll post about what I'm doing as I do it." type of thing, but I'll try to go over some of the basics now. In fact, if you keep the MongoDB documentation site open for reference as you're coding, I guarantee that most queries you'll need won't be that hard.
Those of you coming from a strong love of MySQL will appreciate part two here. I'm going to go over what will replace your IN() and NOT IN() and I'll even brush on LIKE at the end of this post.
Equal To and In ($in)
So, probably your most basic query will be finding something by a specific value. We typically look up by id and we can do this in Lithium and it's been documented elsewhere. So if you've used Lithium and you've done this type of query, this will bore you...But it's good to point out that the following two conditions are basically the same.
$conditions = array('title' => 'BBQ Chicken');
$conditions = array('title' => array('BBQ Chicken'));
You can simply use a string value for the "title" key (the key being the field name in your collection in MongoDB). These aren't literally the same thing of course, the array() means to go get multiple. So you can add to that list and you've got yourself an $in basically. Here, these two are also work the same:
$conditions = array('title' => array('BBQ Chicken', 'More Chicken'));
$conditions = array('title' => array('$in' => array('BBQ Chicken', 'More Chicken')));
I suppose a difference here is that the first set of conditions would work if you were using MySQL or MongoDB with Lithium. The minute you start using specific operators for MongoDB (all those with dollar signs) then you're no longer coding in a database agnostic fashion. Which probably isn't a real big deal, unless you were trying to make some sort of application that could run with whatever database desired.
Not Equal To ($ne) and Not In ($nin)
Of course we have the opposite available to us as well. These will not be database agnostic, but you can run:
$conditions = array('title' => array('$ne' => 'BBQ Chicken'));
$conditions = array('title' => array('$nin' => array('BBQ Chicken', 'More Chicken')));
$ne being "not equal to" and $nin being "not in". The equivalent of <> and NOT IN() for MySQL users. You can probably start to see how all the operators are translated into this array format in Lithium's Model::find() method. Once you see a few you can pretty much assume the rest will be similar.
LIKE, as in Like Regular Expressions
So real quick I'm going to touch base on the equivalent of a MySQL LIKE in MongoDB. MongoDB is actually way cool in that it lets you run regular expressions! You can't simply put title => '/regex/'... That won't work because you're not technically defining a regular expression, you're defining a string. PHP has no RegExp() object class like JavaScript does. However, that PECL extension you installed for MongoDB does have a class to help you out here. So in order to use Lithium's find with a regex, you'll write something like this:
$conditions = array('title' => new \MongoRegex('/chicken/i'));
This is of course a very basic regular expression, but you do have the ability to create quite complex expressions and also take advantage of some flags; you can look here for the currently supported flags. Above you can see that I'm using the case insensitive flag. Those conditions would return me all of my chicken recipes.
Lithium also accounts for MongoRegex() as well so you don't actually need to create a new MongoRegex() object yourself. You could also write:
$conditions = array('title' => array('like' => '/chicken/i'));
For those of you not familiar with Lithium, let me glue it together for you. The Model::find() method is extremely powerful and simple to use in Lithium and it will help you make queries very quickly. You will write less code, things will look organized, and you won't be pulling your hair out. Not that I think using the straight up MongoDB extension is all too complex, but Lithium makes things a little nicer for you.
$recipes = Recipe::find('all', array('conditions' => array('title' => array('like' => '/chicken/i'))));
In a simple example, but keep in mind that aside from "conditions" you also have keys like "limit" and "fields" available to you in order to return a more specific set of data. $recipes here will be an object with all of my recipes with chicken in their titles. $recipes->data() would then return an array from that object for me to use nicely in my view template. That's one powerful short line of code. Typically to run the query you would be talking about establishing the connection first. You'd write more lines of code. Lithium makes things pretty easy, right?! Due to the speed of MongoDB this also might serve as your site's search engine. Not too shabby. Stay tuned for more, I'll get back to some of the more complex (and sometimes strange and probably not often used...but fun) queries you can make with Lithium and MongoDB.
MongoDB Queries with Lithium: Part One
Ok, so this will probably be a whole big long series because there are a real good handful of different types of queries you can make with MongoDB. Combine that with the complex objects that you can store in the database and you really can get quite complex. Of course I also urge you to think about database design even if MongoDB is so easy that you dive in and just simply forget to think and draw out a schema map. I mean you have regex and all sorts of crazy stuff available. Check out this MongoDB documentation page for more.
So how does one access all this using the friendly Model::find() in Lithium? If you're like me, you're probably coming from CakePHP and the find() will make a lot of sense. You'll be comfortable specifying the conditions key and order, etc. But you won't know what to make about some more of the complex things. So in this series I'm going to provide some simple examples of how to go and form those advanced queries using the Lithium framework.
The Task at Hand
So today I came across a situation where I have an array of data stored in MongoDB. I'll give you the exact context, this is for my Family Spoon project. This is the recipe record holding an array of data for all the families it's being shared with...Or requesting to be shared with upon admin approval. So this "families" array has multiple items each with keys of "family_id" and "approved" and "request_date" and "approval_code" and what not. All different data types right? Strings and booleans and timestamps, oh my! So on some overview admin page we want the user to see all these recipes that they need to either approve or reject. We also need to only show to other people only the approved recipes that are being shared on some other page.
So you're talking about your typical AND operator in MySQL. You're saying go get me records where the family_id is this AND the approved field is that. Great and using the JSON we use dots to get into those arrays and it translates to:
$conditions = array('families.family_id' => 123, 'families.approved' => true);
Or does it? Mwuahahaha....No it actually won't give you the results you expect. What that will do is give you all recipes where the family id is 123 and all recipes that are true. I know what that sounds like...BUT...not where both are strictly the case. So you're getting all these recipes that aren't approved, what gives? That's kinda more like an OR situation with MySQL right?
A little check into the MongoDB docs under the "Reaching into Objects" section should help clarify. It says blah blah blah, "subobjects have to match exactly", blah blah blah. Crap. So then what?
$elemMatch To the Rescue!
Oh, we use this $elemMatch thingy. It allows us to specify these conditions for more complex objects how we would expect. The question is does Lithium have some array key called 'elemMatch' to use like 'conditions'?? No it doesn't and you don't need to make some custom query...You can use find(). So here's where the thinking cap went on...Er, the trial and error cap. Lithium DOES look for $ in conditions. So how do we write them? Like this:
$conditions = array('families' => array('$elemMatch' => array('family_id' => 123, 'approved' => true)));
Make sense? I don't think it's real obvious, but it's pretty simple looking at it. It's just that it's not well documented (yet). So this will build out the query the way it needs to be and return the results you'd expect, we wouldn't see any "approved" = false recipes in the results. Note that in this case we also are not using any dot notation. Keep in mind that running conditions like the following are also perfectly valid and work.
$conditions = array('families.family_id' => 123);
It just will give you simply all recipes with the family id of 123. So in some cases you will use the dot notation and in other special cases you'll need to see some of those operators with the dollar sign. So, fortunately, Lithium does allow us to use those operators and you do not need to make any sort of custom query and forfeit the use of the find() method. Hooray! Just keep one very important thing in mind...Your find() call may not be database agnostic anymore so if you're using multiple database types or want to make an app database agnostic, watch out. More to come soon.
Moving from CakePHP to Lithium: Helpers
I love CakePHP and I love Lithium. I imagine many other people will also love both or one or the other or parts from one or the other or neither or enough already. I also suspect that many people will find themselves moving from CakePHP to Lithium. I believe it will be a somewhat common and natural transition. However, we're missing something. Oh right, tons of helpers and other classes!
But wait! There already exists a few helpers for Lithium that act like CakePHP's helpers! So the whole point of this blog post is to say, "Hey! Migration might not be as bad as you think after all." Ok, ok, a few helpers is really not a solution for alllll of the tools CakePHP has but these are, well, helpful. I think Alexander Morland (alkemann) did an amazing job re-writing some helpers for Lithium. You can grab the helpers from his Github repository here. So I wanted to share my discovery and spread the word.
Combine & Minify Assets with Lithium
li3_assets is a nice Lithium library that I've been working on for the Lithium php framework. It is a very easy to configure (and use) library that will combine and optimize your assets all into one file. How does this impact your web site? Well really, it's how traffic won't impact your web server. What happens is instead of say 5 or 6 JavaScript files if you're using jQuery and a handful of plugins, you'll have just one and it will be minified or packed for you. So you don't even need to be using a minified or packed version of the script. In my test here, I saw 12 requests go down to 5 requests and 302Kb page size drop to 187Kb. The numbers really can be staggering depending on how many scripts (and css files) and whether or not they were originally minified or packed or not. This helps overall performance in a website and helps when you have large amounts of traffic coming to your website. The server will serve out less requests and smaller amounts of data so it can handle more visitors.
For JavaScript you have the choice of using JSMin or Packer and for CSS you have the choice of using CSSTidy or a simple whitespace and new line removal. This removal code is very simple, but also very safe. The reason I left a few options for both is because sometimes when you start minifying and packing code, things break. It's rare, but possible. Some of these tools have options and those can be passed as well in the configuration.
As an added bonus, this library also will run less files through phpless. Less is a CSS shorthand syntax that will be converted into actual CSS files. The idea is to speed up your development time. After the files are run through phpless and converted, they are then run through CSSTidy and combined into the single CSS file.
These single combined and condensed assets will live in a directory of your choice and be named with a hash string. This hash was generated from all of the assets used. This way every page that has different assets (JavaScript and for the CSS), will have a different combined hash and therefore different file. Updates? If you have an update to a CSS or JavaScript file, you'll have to remove this hashed file so it can be regenerated. In other words, you may not want to enable all this until you're live with your site.
What's this about images? Images can be "optimized" as well. All images placed with the Html image helper on any given template can be output as base64 data URI's if you so choose. The major drawback to using data URI's is that they don't work on IE 6 and IE 7. You can find some JavaScript solution to this problem, ignore this problem, or don't use data URIs. The benefit? Well, if you're caching your view templates, you've now just embedded all images within the HTML code of your view template. So you can probably take a page down to about 3 requests. One for the JS, one for the CSS, and one for the HTML code plus images within. Now you're really starting to save the server quite a bit of work.
So how easy is this to use? How do you use it? Lithium makes this simple. You will run the Libraries::add() method and add li3_assets. Within the same call, you'll pass all of the configuration options. Then in your layout you'll call $this->optimize->styles() and $this->optimize->scripts() instead of $this->styles() and $this->scripts(). So it runs based on the "scripts for layout" feature. Where any script you place within any of your view templates that contain the array option "inline" as false, you will have those be put into the layout template up top within your head section (or wherever you chose in your layout template). The li3_assets library's helper basically intercepts these assets and runs the magic. It then simply returns the HTML code for the assets to be embedded into the page. Simple. So this makes it nice when you want to turn off the optimization. It also makes it flexible so you can have certain layouts that optimize and others that do not. Here's the code all formatted. First, the library configuration.
Libraries::add('li3_assets', array(
'config' => array(
'js' => array(
'compression' => 'packer', // possible values: 'jsmin', 'packer', false (true uses jsmin)
'output_directory' => 'optimized', // directory is from webroot/css if full path is not defined
'packer_encoding' => 'Normal', // level of encoding (only used for packer), possible values: 0,10,62,95 or 'None', 'Numeric', 'Normal', 'High ASCII'
'packer_fast_decode', => true, // default: true
'packer_special_chars' => false // default: false
),
'css' => array(
'compression' => 'tidy', // possible values: true, 'tidy', false
'tidy_template' => 'highest_compression',
'less_debug' => false, // debugs lessphp writing messages to a log file, possible values: true, false
'output_directory' => 'optimized' // directory is from webroot/css if full path is not defined
),
'image' => array(
'compression' => true, // uses base64/data uri, possible values: true, false
'allowed_formats' => array('jpeg', 'jpg', 'jpe', 'png', 'gif') // which images to base64 encode
)
)
));
This shows all of the options, but there are defaults. Then in your layout template put the following within the head section of your template:
echo $this->optimize->scripts(); echo $this->optimize->styles();
That should do it. Now any script in any template using that layout defined like this:
echo $this->html->script('scriptname', array('inline' => false));
...Will be sent to the layout and intercepted and added to the list of scripts to be processed. The same goes for CSS as well.
To convert all images within a template using the Html::image() helper method, you'll simple put at the top of the view template:
$this->optimize->images();
This doesn't output anything, but it does trigger a method that will apply a filter to the Html::image() method. Filters are a real nice feature with Lithium. Now any call to the image() method will be intercepted and the data will be converted to a base64 data URI and returned. I think the use of images as data URI's is limited, but can be a nice feature to have. I think it's especially handy on certain pages where you know a lot of traffic will hit and also helpful for mobile devices. Remember that making another request (connection) takes time and while we don't notice it on high-speed internet, mobile devices will notice it. It also changes when images get loaded and rendered in a browser as well. So I feel it's an under used trick of the trade.
Again, you can grab this library from the repository on the rad-dev site. http://rad-dev.org/li3_assets.
Using Swiftmailer with Lithium
The Lithium framework is a very flexible framework and it gets along quite well with other classes. It has auto-loading features and utilizes namespaces in PHP 5.3. So any class or library of classes is typically pretty easy to use. Take for example the wonderful Swiftmailer project. This library makes sending mail via mail, sendmail, or any smtp server (including Gmail) very easy.
So how does one get it working with Lithium? Quite easy. You can simply move all of the Swiftmailer files into a folder under your app's libraries folder, named something like "swiftmailer" ... Why not? Obvious enough. Under there you should have a lib folder with all of Swiftmailer's classes and it's auto-loader.
Great. You're actually half done. The next half is to include the Swiftmailer library and auto-loader in your bootstrap. You could of course also just follow the directions on the Swiftmailer site and run require_once(...); somewhere in your method of some class, but we want to do things the Lithium way. So use Libraries:add('swiftmailer'); instead. Though, we will need to pass some options to bootstrap that auto-loader.
Libraries::add('swiftmailer', array(
'bootstrap' => 'lib/swift_required.php'
)
);
That's all there is to it. Now you can use Swiftmailer anywhere in your application. You just should note that you're working with namespaces in Lithium and the Swiftmailer class doesn't use a namespace within your application. So you'll need to call its classes like so:
$transport = \Swift_MailTransport::newInstance();
$mailer = \Swift_Mailer::newInstance($transport);
$message = \Swift_Message::newInstance()
//Give the message a subject
->setSubject('Test Message')
//Set the From address with an associative array
->setFrom(array('your@email.com' => 'Your Name'))
//Set the To addresses with an associative array
->setTo(array('to@email.com'))
//Give it a body
->setBody('Here is the message itself')
//And optionally an alternative body
->addPart('Here is the message itself', 'text/html');
$result = $mailer->send($message);
This would send a message using mail(). You can refer to the Swiftmailer documentation for other usages, but you'll just need to remember to add the first \ slash so you're in the proper namespace. You can also put the "use" command at the top of your class like this:
namespace whatever\may\have;
use \Swift_Mailer;
use \Swift_Message;
use \Swift_MailTransport;
class whatever extends something {
}
Then you won't have to remember the beginning slash to use the classes and when you follow (or copy and paste) from the Swiftmailer documentation, you won't have to really adjust much or think about it. I don't mind adding the slash personally, I don't like to put "use" up top in this case because you're talking about a few different classes that you will be using (the "Mailer", "Message", and "MailTransport") and I just find it a hassle and just makes me write more. Additionally, I may only have one method that actually uses those classes.
Anyway, I hope this helps someone out there with using Swiftmailer with Lithium. I'm sure it's fairly obvious, but that bootstrap feature is really cool and I wanted to put it out there for those not familiar with the framework or those who didn't take advantage of the auto-loader with Swiftmailer and Lithium. There are actually several ways you can use Swiftmailer (and other 3rd party classes for that matter) with Lithium. I just really like how Lithium keeps things consistent with the Libraries::add(); method.
Aspect Oriented Programming: Lithium's Filters
What is aspect oriented programming (AOP)? Well, you could search Google and find tons of information about it and also read Wikipedia. Or you can essentially just understand that it's a very high level approach of handling program functionality, making it really modular in design. IBM has a great article that's a little easier to read.
So how does Lithium handle this idea of AOP? With it's filter system. Since it takes advantage of PHP 5.3 it has the benefit of lambdas and therefore it's filter system was made possible. Essentially, any method you write or many (not all, but many) within the core framework can be filtered. What does "filtered" mean? Well essentially you call a method on the class passing the method as an argument, Class::applyFilter('method' ...); and you will inside the applyFilter() method also define and pass an anonymous function and pass along the chain. Within that function you can perform other logic and then return the chain so that everything can carry on. Or maybe you don't return the chain, maybe you stop right there and exit out with some data. This is basically linear event handling. Each filter is going to do its thing in order as called.
So now what's the big deal? Why is it so much better? Well, using the example of CakePHP's callback methods in the model...Let's say you have one tiny specific situation where you need to perform some logic before you find a record. You could use the beforeFind() callback method. Great, but then let's say you have to perform that in another model. Oh snap, well, we'll just add that into the other model. Then another model later on? Really? Come on the client must be beating you up. Then only at a certain time of day? Under other crazy conditions? Ugh. Ok, so you can understand that you are very quickly ending up with messy, borderline unmaintainable, code. You have to go back to many different places and add in new code. You may even need to write entirely new classes and access methods in those classes to get the job done.
So if instead we applied filters from a different area in our code, we can keep all of our "advice" or ways of dealing with our "cross-cutting concerns" in one place. Furthermore, since we're in an event chain with Lithium's filter system, we can bypass things once we have what we need and structure things in an efficient order.
The new CMS I'm working on, Minerva, will take full advantage of Lithium's filter system. Essentially, it will account for a very large piece of how the CMS is extended with plugins (Lithium libraries written specifically for Minerva). For example, the "Page" model is the main model that deals with records for, well, pages on the site. These pages can be basic simple pages or blog entries or photo galleries or anything really. What "flavors" or "decorates" pages? Libraries. So there's a "blog" library that gets dropped in and poof, there's a blog. In fact, there won't even be any "installation" or database setup required (thanks to MongoDB). Drop the files and literally - poof. Now the blog library has a Page model itself and it extends Minerva's Page model. It adds new schema so we can gain extra fields that we may need for a blog and, more on topic here, it applies filters.
One filter it applies is to the model's find method. It has an index listing method in the controller and when called, it will make a call to the find method to get the records. The blog library's filter says, "Hey, since you're talking about me, go grab just my records." Now you have an index listing of blog entries instead of all pages. Sure, this is a very basic example and you could simply have the controller method pass along a URL parameter that changes the find query to only return records belonging to the library just the same. Let's say it was just a tiny bit more involved so that each time we added a new library, we'd have to go back and add in some more code so we can actually handle the new library.
Ok, so you can see in this admittedly poor example (use your imagination for more sophisticated cases), that you have to ultimately keep going back and altering a "core" piece of code each time you add in some new functionality. Maybe it's not the "core" framework, but still in our case the "core" app that we really don't want to touch because when there's an update, we want to ensure we can get that update without conflict. With the filter system, you don't have to touch the core app. It's a more hands off, more abstract way of handling the concern. Also look at where it's been set? It's been set inside the 3rd party add-on code. The main application doesn't even have a clue about what's going on and the core code base was never touched. It's not dependent at all. All this without having to setup some big API system that adds more beef to the app and has to have every little detail worked out. Then what if our "API" updated? Oh, well then we have plugins for the CMS that are for version 1.x and plugins for version 2.x etc. You'd need to update the plugins to run with the latest CMS. Minerva specifically aims to not fall into the same problems that most other CMS' out there do.
Of course you can also get away solving some of these problems with simple class extension, but you'll ultimately run into problems. Obviously maintaining the code. Say you do extend and override some methods then one day you pull down the latest framework code from the repository and poof your site no longer loads. You have a white screen and you have no idea what happened. Then you have to debug. Yuck. Hmmm, and wouldn't a nice logging system help you out here? Oh look, another great use for the filter system.
So Lithium's filter system is extremely valuable. It's something that I believe will distinguish the framework from others and will help developers build faster and more maintainable code. Stay tuned for some more examples and also more information about my new CMS, Minerva. You can actually dive into some of the code and check out some example uses of the filter system in Minerva's code found on github. Minerva is still in it's early stages and is subject to change, but it should accurately represent the direction it's heading and the blog library's Page model should give you an easy to understand example of the filter system.




Social Networks