Você está na página 1de 18

Ocular Guide - version 3.0!

Lonnie Ezell

Ocular Guide 3.0

Welcome to Ocular
Ocular is designed to be the most flexible template and layout library for the CodeIgniter
PHP Framework. It is well on its way to providing every feature you will need for your web
applications, including:

Wordpress-like parent/child themes


Controller-specific theme pages
Basic asset management designed for high client-side performance
Improved flash messages
Robust partial-view handling
and more...

This short book is intended to act as both a guide to introduce you to the concepts of
Ocular, as well as a detailed reference manual.

1
Ocular Guide - version 3.0! Lonnie Ezell

Concepts
Ocular is designed to be the most flexible theme engine available for CodeIgniter. With that
flexibility comes a little bit of a learning curve, but I think youll find that the actual day-to-
day use is very simple.

Themes
Themes are at the core of Ocular. Nearly everything that Ocular does involves the use of a
theme, so lets take a quick look at what themes are to Ocular.

Youve Got The Look


Every web page has a common set of elements that will, typically, wrap the page content.
This might include a header, footer and a sidebar. It is these common elements, combined
with the CSS and Javascript that make up a theme.

While you could simply call CodeIgniters $this->load->view() method to load in your
themes files, that quickly becomes a maintenance nightmare. Not to mention a time-sink
for a developer.

Thats where Ocular comes in. It provides a simple way to almost automatically wrap your
page content (or your views) within this common markup.

Most web applications will have a minimum of two completely different looks. One for the
public facing pages, and another for the admin pages. In Ocular, these would be two
different themes, each with their own HTML, CSS, and Javascript. That way everything is
nice and isolated from each other, and you dont have to worry about breaking the public
facing pages while tweaking the look of your backend.

You might also use themes to provide a different look for all of your authentication pages,
like login, signup, etc. It might be necessary to create a different theme for forums, or
some other part of your site.

2
Ocular Guide - version 3.0! Lonnie Ezell

Just Like That - Only Different


A common scenario on web sites is to have a common theme used across all of the
public-facing pages, with variations for the home page, blog pages, and maybe even any
store pages.

This is all still the same theme. After all, the overall look of the site doesnt change, just the
placement of a few items, or a smaller header, etc.

Ocular calls these Layouts, and you can have as many as you want.

You might have your main layout built to handle the vast majority of your site. This file
would be the index layout. Then, you need to customize the home page enough that it
deserves its own layout, so you create the home layout. You could do the same for the
blog pages in--you guessed it!--the blog layout.

All of these layouts are stored together under the theme folder so nothing gets misplaced.

And you can specify which layout to use whenever you want. No questions asked.

Fiddly Bits

Now you have three different layouts, but youre repeating code left and right and its
becoming a nightmare. No problem.

Using blocks, you can rip that common code for the header and put it into its own file in
the theme. Then you can call theme_view(header) in each of your layouts and--bingo!--
youre keeping yourself DRY (Dont Repeat Yourself, in case you havent heard of that
one.)

Every Asset In Its Place

As your application grows, so does the amount of CSS and Javascript that needs to be
used on each page. You can take a page from how Ive heard Facebook does things
separate your code into only what is needed for that page.

3
Ocular Guide - version 3.0! Lonnie Ezell

You place any common code that is used throughout the site in a file called screen.css, or
global.js, and Ocular will automatically load it for you.

Then you realize that certain CSS is only used to style pages from one particular controller.
You dont really want to load that for every other page, do you? Of course not! Thats just
wasted bandwidth that you (or your client) has to pay for. Create a CSS or Javascript file
that matches the name of the controller, and Ocular will automatically load that, too.

Got custom libraries that you use? Or CSS common to two or more controllers, but not
used enough to be called global? Then create your own CSS or Javascript file and, in your
controller, tell Ocular to load it by using the Assets::add_css() and Assets::add_js()
methods.

A River Flows Through


Wouldnt it be nice to have a base theme that you use for all of your public-facing websites
that you can simply add another CSS file to and have a whole new style. Or maybe your
app needs to provide multiple themes that the users can choose, and you want a parent
theme to provide all of the structure, and child themes that require very little work to get
up and running.

Yeah. You can do that. Thats what Ocular is built for, actually.

Any theme can be used as the parent theme (as long as Ocular thinks it is the default
theme). To change the look, you simply create a new folder to hold your theme, drop in the
necessary files (but only the ones that changed!) and tell Ocular to use this new child
theme by calling Template::set_theme(new_theme).

At its simplest, you could just provide a new screen.css file to whip the new theme into
shape, and call it a day. Dont worry, youll still get all of the styles from your parent theme
loaded also.

However, you can get as crazy as you want to. You can create a header.php file in your
child theme that will override your parent themes header.php file, while still using
everything else. Or override the parent themes looks for a single controller (the blog?) in
your child theme. The possibilities are endless.

4
Ocular Guide - version 3.0! Lonnie Ezell

And Were Just Getting Started


There you have it: the thousand-mile view of Ocular and its possibilities. Hopefully, this
gives you enough information to grasp the flexibility and power that Ocular gives you.

While the overview provides a solid grounding in the concepts used, it is by no means an
exhaustive look. The power is in the details, all of which Ive tried to make as simple to use
as possible. There are also some convenience features that havent been touched on.
Throughout the rest of the book, well take a more detailed look at all of these in more
detail.

A Quick Word About Performance

While Ive tried to keep things moving along as quickly as possible, any time you have this
much flexibility (and this much searching through the file system), you have to give up a bit
of performance. Theres very fews ways to get around this, but I am brainstorming some
ideas to improve the performance where possible.

The best way around this is to make careful use of CodeIgniter Reactors built-in Cache
library. When caching, especially to the file system, you should always take care to make
sure the caching isnt slowing things down.

5
Ocular Guide - version 3.0! Lonnie Ezell

Getting Started
Ocular is designed to work CodeIgniter 2.0 and higher, so you will need to get that
installed and running, first.

Ready?

Installation
Installation of Ocular is simple.

1. Download the latest code from GitHub (https://github.com/lonnieezell/


OcularTemplateLibrary)

2. Unarchive the contents. Make sure to retain the directory structure if you your
unarchiver asks.

3. Following the directory structure, copy the files to your application's folders. The files
that you should be concerned about are:

To get a small lift in your apps


performance, you should consider
combining the 2 config files into a single
file. Typically, I combine these two files
with other application specific settings
into a single file to help minimize the
number of files loaded at run-time.

6
Ocular Guide - version 3.0! Lonnie Ezell

Your First Controller


As a quick example of using Ocular, let's convert the standard CodeIgniter welcome
controller and view to use Ocular.

The Welcome Controller

Modify the welcome.php controller that ships with CodeIgniter to look like:

class Welcome extends CI_Controller {

function __construct()

parent::__construct();

$this->load->library('template');

//---------------------------------------------------------------

function index()

Template::render();

//---------------------------------------------------------------

If you try to load the page in your browser now, you'll get an 404 error, because it cannot
find the proper view. By default, Ocular uses the name of the controller and method to
determine which view to find. Since the controller is Welcome, and the method is index,
Ocular expects to find a view at /application/views/welcome/index.php.

7
Ocular Guide - version 3.0! Lonnie Ezell

To get things rolling, create a new welcome folder under your views folder, and rename the
welcome_message.php file to index.php. Move it into your new folder, reload the page in
your browser, and you're good to go.

Your views folder should now look like:

Loading Ocular
Like any library, there are several ways to load Ocular.

1. Autoloading - load the Ocular library automatically by placing it in the config/


autoload.php libraries array. You do not need to load the config file, since Ocular will
automatically load it.

2. Controller Loading - you can load it at the beginning of every controller, though this is
not that convenient.

3. Base Controller - if you are subclassing the Controller (which I highly recommend) you
can also load the library in your new Controller.

While running a number of simple tests, it appears that loading it in the controller can be
the fastest option. Despite threads on the forums discussing the speed issues with
autoloading files, I've found that to be the second fastest option, and definitely the most
convenient. As with any benchmark that requires disk access, your mileage may vary.

Configuring Ocular
All of Oculars configuration settings can be found in application/config/ocular.php. The
file is split into two sections. The first deals with the template settings, while the second
focuses on the assets.

8
Ocular Guide - version 3.0! Lonnie Ezell

$config['template.site_path']

The path to the root folder that holds the application. This is used as the reference point for
everything template related. All other settings are assumed to be relative to this location.

It defaults to FCPATH.

$config['template.theme_paths']

An array of folders that Ocular will look in to find themes. There must be at least one folder
path at all times. By default this folder is application/themes.

For many sites, you will never need more than a single path, but there are occasions when
you might want separate locations. For example, you might want to keep your core
templates separate from any user-contributed templates, or separate your forum themes
from your site themes.

$config['template.default_layout']

This is the name of the default layout that is used if no other layout has been specified. By
default, this is the index.php file.

NOTE: Do not include the .php file extension.

$config['template.ajax_layout']

The name of the layout to be used when the page is displayed via an AJAX call. By default,
this is the ajax.php file.

NOTE: Do not include the .php file extension.

$config['template.default_theme']

The theme that is used by default when rendering pages. The default theme is called,
oddly enough, default.

$config['template.message_template']

The template used when displaying flash messages via the message() method.

$config['template.message_template'] =<<<EOD
<div class="notification {type} fade-me">

9
Ocular Guide - version 3.0! Lonnie Ezell

<div>{message}</div>
</div>
EOD;

The {type} and {message} fields are placeholders for the data you specify and must be
present.

$config['template.breadcrumb_symbol']

The symbol displayed between elements of the breadcrumb. Defaults to : .

$config['assets.base_folder']

The base folder (relative to the template.site_root path) that all of the assets are stored in.
This is used to generate the url and the relative file path. Defaults to assets.

This should NOT include the trailing slash.

$config['assets.asset_folders']

The names of the folders for the 3 main types of assets. These default to css, js, and
images, but you can easily change them to match your preferred application structure.

$config['assets.asset_folders'] = array(
'css' => 'css',
'js' => 'js',
'image' => 'images'
);

$config['assets.js_opener']
$config['assets.js_closer']

These are used to wrap around all of your inline scripts. This is a convenient way to include
jQuerys $(document).ready(), or head.js head.ready() wrappers.

$config['assets.js_opener'] = '$(document).ready(function(){'. "\n";


$config['assets.js_closer'] = '});'. "\n";

10
Ocular Guide - version 3.0! Lonnie Ezell

Rendering Views and Layouts


We already talked about Layouts, above, but the simple version is that a Layout defines
the base look for your website. It is the foundation that your other views get rendered in.
They make it easy to provide consistent look throughout your application.

What about Views? They are simply the standard views that youre used to working with in
CodeIgniter. Nothing special there.

The special thing is how you get it to display.

Rendering A View
You can render a view from within any controllers method, by simply calling:

Template::render();

Ocular will look for the view in application/views/controller/method.php. The controller


and method names define where the view is found. If you are in the Welcome controller,
and running in the index method, then your view would be application/views/welcome/
index.php.

Easy as pie.

If you need to change the view it is using for any reason, a little bit of this will do you:

Template::set_view(welcome/again);

When you set your own view, it is often necessary to list the folder(s) it is located in, relative
to the views folder.

View. Meet Layout.


When you call the render() method, Ocular first renders your layout file. Inside of the layout
file, you must have one simple line:

11
Ocular Guide - version 3.0! Lonnie Ezell

<?php echo Template::yield(); ?>

This is the line that lets all of the magic happen. Inside the yield() method, your view is
rendered and stuffed into that location, surrounded by whatever headers, footers,
sidebars, blocks and what-have-yous that you see a need for.

Which Layout?

By default, Ocular looks for a layout file within your active theme (or the default one, if
youre not using more than one) called index.php.

However, if it finds a layout matching the name of the currently running controller (say,
welcome.php), then it will use that layout instead.

If it doesnt find either of these layouts in the currently active theme, it will search through
the default theme for those files, and render from there, if they are found.

If you need to choose a different one, just pass the name along as the only parameter to
the render() method:

Template::render(new_layout);

Theme Views
Its often a necessity to break out common elements, like the header, into a file that can be
shared across multiple layouts. This makes it so theres only one spot to update all pages
in your site. Kinda convenient, that. You might have heard of these being called view
fragments, or partials. Were going to keep things simple and call them theme views.
Mostly because they can change with each theme, and theyre, well, view files.

To render out one of your view files takes just one line of text inside your layout where you
want the view to show up:

<?php echo theme_view(welcome/index, $data); ?>

Note that you can pass in additional data arrays, just like any CodeIgniter views, if you
need to.

12
Ocular Guide - version 3.0! Lonnie Ezell

Theme views will also cascade from the active theme to the default theme. So, if youre
trying to render out the header view and it cant be found in the active theme, but it is
found in the default theme, youre good to go.

Blocks
Blocks can be thought of as small areas of a page that have been set aside for content,
but that arent required to actually put content there. Kinda of like a parking spot for HTML.

In your layout file, you would reserve, say a sidebar, room by calling:

<?php Template::block(sidebar, partials/sidebar); ?>

The first parameter is just a name for the block, that you can reference it by later.

The second parameter is the default view that is used, if nothing else has been specified.
This can be left blank.

An (optional) third parameter allows you to pass an array of key/value pairs to the view.

Another (optional) fourth parameter can be set to true to tell Ocular to look for this view
inside of the theme, not in the standard view file locations.

At this point, your sidebar has his spot reserved, and default content that will show up on
all of the pages. What happens on the Contact Us page when you need a different
sidebar? No problemo. Observe (from within your controller):

Template::set_block(sidebar, new/sidebar);

And youre good to go. Again.

Dynamic Data
At least thats what I call it. Here Im referring to the $data variable you would typically send
along in your $this->load->view() call that becomes magically available to your views.

13
Ocular Guide - version 3.0! Lonnie Ezell

Ocular handles this with the set() and get() methods. (I know, creative naming....)

To make a variable available to your view, you use the set() method:

Template::set(var_name, $data);

If var_name happens to be a string, and $data actually has a value, then that $data will be
available to your views as $var_name. Nothing tricky here.

If var_name is an array of key/value pairs, then all of those values will be made available
within your views under names matching the key.

If, however, the var_name that you use matches one of the Template class own class-
vars, you will be setting that class-var. This means you can change default/active themes,
turn debug mode on/off, and other (hopefully non-evil) uses.

$var = Template::get(var_name);

does pretty much what youd expect: the opposite of Template::set().

Flash Messages
CodeIgniters Flash messages (through the session class) have one major drawback: they
only work if the page has been refreshed, either through a redirect or user interaction.
Sometimes, though, we need instant feedback, and we dont need to hit the server with
more HTTP requests. Thats why Ocular provides its own flash messages.

While only a single message is supported at a time, that is typically all that is needed, as
these messages are meant for simple status updates (like, Yo! The hard drive crashed
while saving your resume!). Setting a message is fairly straight-forward. In your controller:

Template::set_message(This is your message., success);

The first parameter is the actual message itself.

The second parameter is simply a CSS class-name that will be attached to the markup
specified in the config file.

14
Ocular Guide - version 3.0! Lonnie Ezell

Now, in your view file, wherever you want this message to show up, just so:

<?php echo Template::message(); ?>

Just in case I wasnt clear earlier, Oculars messages work both with a page refresh AND
without. When the page is refreshed (and the session library is loaded), Ocular actually
uses the session libs own flashdata with a name of message to store it across the
refresh.

AJAX
AJAX is handled pretty simply in Ocular. Theres actually only 2 things that we worry about,
but theyre both pretty helpful.

The Layout

While not always necessary, often in your code you will want a certain layout file to be used
for AJAX calls. This is probably going to be a mostly empty view file, but might contain a
common JS event that gets triggered when the page is loaded, etc. Or you might just not
want to bother refactoring your code so you dont have to worry about Template::render()
getting in the way. No worries.

Simply create a new layout called ajax.php in your theme, and that layout will be used for
any AJAX calls.

The Redirect

Part of the spec says that when youre in an AJAX call, you should be able to redirect to
another location, and still be considered part of that call. Most of the times, this is great.
There are the occasional times, however, where the action was a success and you want to
bust out of the AJAX call, and do a full-page refresh to a new location. We got you covered
with our own version of CIs beloved redirect() function.

Template::redirect(path/to/new/page);

What this does is to throw some javascript back at the page that will do the actual redirect

15
Ocular Guide - version 3.0! Lonnie Ezell

to the page you wanted to go to. Nothing crucial, but nice to have on your side when you
need it.

Template Utility Functions


The template class also provides a handful of small convenience methods that help out
with little page display-related issues.

Check Class
The check_class() function is meant to be used within your primary navigation, and
performs a very simple check to see if the first parameter matches the name of the
controller that is currently running. If it does, it spits out class=current.

In your views:

<ul id=nav-main>

<li><a href=# <?php echo current_class(welcome) ?> >Home</a></li>

<li><a href=# <?php echo current_class(about) ?> >About</a></li>

</ul>

Check Method
The check_method() function is identical to the check_class() function, above, except that
it is meant for sub-navigation based on the method currently being executed (according to
the router).

Breadcrumbs
When you need to display some basic breadcrumbs in your layouts, youve got a quick
little function to help you out:

16
Ocular Guide - version 3.0! Lonnie Ezell

<?php echo breadcrumb(); ?>

This creates a basic breadcrumb that is a series of links separated by a symbol of your
choosing, that would look something like:

Home : Pages : This Page

The breadcrumb is built from the URI segments of the current page. If the default uri
segments will not work for a page in your application, you can pass an array of key/value
pairs that represent the crumbs. The key of each pair is the value that will be shown, while
the value of each pair represents the url segment to pass into it.

Asset Handling
The Assets library makes adding CSS and Javascript to your layouts, both at design-time
and run-time, as simple as possible. It works hand-in-hand with the Template library and
the parent/child relationship between themes.

Global Styles
As web applications get larger, we can start using different tricks to keep the end-users
performance high. One that I heard Facebook does is to keep a base set of global styles
that apply to damn near every page in their site. Then, on each individual page, there might
be some styles that are needed for only that page. Ocular makes this easy.

<?php echo Assets::css(); ?>

When you put this call in the head of your layout, Ocular will automatically look in your
default theme for a stylesheet called screen.css. If its found, its included. Then, we search
through your active theme for a file of that same name.

17
Ocular Guide - version 3.0! Lonnie Ezell

This allows both stylesheets to be included, and lets your active (child) theme only include
the changes needed, not recreate the entire stylesheet.

Just the Styles, Maam


<?php echo Assets::css(global); ?>

By using a first (optional) parameter, you can tell Ocular to look for a particular file, or files,
and ignore any other styles. If a single filename is passed, it will only create a single link for
that file. If an array of filenames is passed in, it is merged with any styles that have been
added to the collections (via add_css()) otherwise, it will include any styles that have been
added with add_css below.

Print and More


<?php echo Assets::css(global, print); ?>

The second parameter is used to change the media type for that stylesheet(s).

But, I dont want no kids!

If you dont want your stylesheets to be inherited from the default theme, you can pass
true as the third parameter.

18

Você também pode gostar