I have taken to experimenting with stitching panoramic images together. The one
above is of Bear Lake in September of this year. We sped around the lake at
sunset hoping to get to the eastern shore in time for the shot. I ran out of
the truck down onto the stony beach and started shooting.
The resulting photo has has had little post work done in lightroom, but was
stitched together using photoshop with a dash of content aware fill to fill in
where the distortion curved down into the blue sky and took out a chunk of the
right-most mountain.
As of PHP 7 the function described below is no longer neccessary as it’s been
superceded by the Null Coalesce Operator.
Null Coalesce allows a nice bit of syntactical sugar for a checking if a
variable is set and then returns that variable if it is or some fallback value
if it is not:
Outputs the value of $title if it is set or ‘Blog Title’ if it is not. It is
the same as doing:
My favorite helper function for CodeIgniter is a ridiculously simple function
that has an amazing amount of utility. I stole, at least the idea of, this
function from LemonStand and it has since made its way into nearly every CMS
that I have worked on:
At first this doesn’t really seem to be doing much, after all at first glance
it looks like it is nothing more than a wrapper for isset, but this improves
heavily upon isset in two very important ways. First, let’s look at how this
function works.
In the function definition we are taking a reference to a variable. Recall, a
reference is pointing at the memory, not value, of a variable and so we can
actually pass to our helper function a variable that has not yet been
initialized. This saves us from receiving a notice that the variable does not
exist. Our call to isset thus checks our memory to see if it is actually
referencing a variable or nothing at all. If it is referencing an actual
variable it returns that variable, otherwise it returns null (our default
default) or whatever value has been assigned to $default.
The utility of this is best expressed in handful of examples. The biggest use
of this is in a view. Let us look at a view constructed without the use of our
helper function:
In a sizable view the above can get quite long and quite cumbersome to
maintain. Each call to isset is checking to see if the controller actually
passed the value on to the view ( $title or $content ). If we did not do
this we would get a notice from PHP. Sometimes this is resolved by
programmers by using the error suppression symbal (@), however the notices
will still end up in the logs of many frameworks that strictly check for
errors. Contrast this with a view using our helper function:
The above is a much, much more concise view that is easier to read and is still
a strictly valid snippet of PHP that generates no warnings or notices.
Once we start to use this helper function regularly all different kinds of uses
come up for it, for example we can use it to see if a model returned a value:
The above snippets are fairly simple, but let’s walk through them. In both
instances we need to pass some page object on to the render method. An error
occurs if it does not get a valid page object so we must check after
retrieving a page that it actually exists. In the first snippet we use four
lines of code to first get a page by $url (the value of which is set
somewhere else). Now if the pages model returns nothing then we enter a
conditional statement that retrieves the 404 error page.
However, with the use of our helper function we can shorten the code in half
and remove the conditional all together make it a much more readable snippet of
code. The first line of the second snippet simply passes the return of the
pages model and the get404 method into our helper function which returns
the first if it returns something or the latter if it does not. The only
downside is the additional load since the 404 page would also need to be loaded
concurrent to the current page with each request, but in most cases this is
going to be negligible.
Having looked at two different uses for our helper function, we can begin to
see that we can get quite a bit out of some very very small functions. If you
have your own favorite one-liner functions feel free to share in the comments
below.
In this article I plan on addressing CodeIgniter’s shortfalls as a framework
for validating objects and introduce a method for improving the validator
classes re-usability.
When To Validate?
The answer to this question is simple: whenever we are dealing with input. The
(incorrect) assumption that CodeIgniter and many web-applications make is that
user input comes in the form of GET and POST variables and a considerable
amount of effort goes into validating inputs via these routes. However, GET
and POST are not the only sources for user input. User input can come via
external sources such as tying into a remote API, an RSS feed, or from the
database itself. From each of these sources we could get an invalid state. In
the case of the remote API or RSS feed this is easy to understand. The API
could change, or the RSS feed could be malformed. In the case of the database
the issue typically appears when data is stored into the database under one
context but is then accessed with a different expectation.
Take for example a database with the following table:
Now say that we inserted a person with name “Bob” and birthdate
“1975-01-01.” This passes the validator going into the database, but later on
we pull this row from the database and use it to construct a plain PHP object
with properties id, name, and birthdate which we pass onto the view and
attempt to output the birthdate with the following line:
This is going to cause an error. Why? Because the date function is expecting
the second parameter to be a UNIX timestamp, but birthdate is already a
formatted date string. Now, we could solve this by changing the schema of the
database or changing the schema of the person object, but it is important to
note that even if we did fix the disparity between the two we would still not
fix the issue that it is possible for the person object to exist in an
invalid state.
So my answer is to when should validation occur is during object instantiation
and setting. The properties of the object should not be able to be set to a
value that the object cannot accept. This places validation clearly into the
realm of the “M” in “MVC.”
Form Validation in CodeIgniter
CodeIgniter’s
documentation
offers a form validation class that makes the above mistake very clearly. It
can only validate the POST super global and doesn’t really offer much of a
solution towards validation of objects themselves. Furthermore, their example
controller oddly mixes the issue of object validation, and thus business logic,
inside the controller which tends to create in many CI application fairly
bloated controllers:
I cannot offer a solution towards adapting the validation class to be fully
object operating without a heavy rewrite of the class, but we can move this
obtuse validation into a distinct model that encapsulates this behavior away
from the controller.
Introducing the Abstract Validator Class
We can get the validation logic out of the controller by moving it into a
Validator class. We begin with an abstract base class since each form will
need their own validator classes:
We take advantage of the fact that the CI god to access the form_validation
object inside the Validator instance to create the validate method which
merely sets the validation rules and then runs them. The Validator has two
properties $rules and $fields which we will use in sub-classes to provide
the CI_Validator rules and fields strings. We can transform the above
controller into the following subclass:
Here we can see how the rules and fields are used as well as how we can extend
the Validator class to add additional unique callback validations. This
simplifies the controller significantly:
The business logic is now gone and the controller is back to focusing on what
it’s supposed to be doing – load resources and running paths.
I have been keeping my own personal accounts for some time in a progressively
growing spreadsheet that after one decade of use, multiple files, and dozens of
worksheets. The entire thing is quite a mess. My solution? Build an app for it!
Pecunia will be a simple budgeting application designed from the ground up for
keeping track of monthly budgets, annual budgets, and keeping a ledger of
individual expenses. With a little bit of work, I should be able to turn it into
a multi-user application to launch as an extension on Kynda.net for public use
as well as an open source repository on Bitbucket.
This also gives me an excuse for a long series of posts going through the steps
necessary to take a spread sheet, abstract it’s logic into models, and implement
it’s functionality into a useful application.
Resources
Pecunia will be built using the following resources:
PHP 5.4
Apache 2.2
MySQL 5.5
Silex
Laraval 4
Update: January 22, 2014
After some consideration, I am opting away from Silex towards using Laraval 4.
It is not that I have suddenly found a dislike for Silex, rather I love working
with it, but that I would like to try my hands at the “latest and greatest” to
see what the big deal is about and to add another tool to my retinue.
I have worked with Code Igniter almost exclusively for the last nine months. In
that time, I have found it to be a massive step ahead over working with some of
the major CMS systems on the market (WordPress, I am looking at you).
Nevertheless, there remains some major architectural and blind spots that exist
in CodeIgniter as a framework. Some of these issues are resolvable
(CodeIgniter’s presumption that you would only ever want to validate the POST
superglobal), while others are inherent in it’s design. In this series I hope to
look at some of these issues that I have found with CodeIgniter, showcase
work-arounds where I can, or simply rant where no good solution exists. Today’s
topic will be of the latter variety.
The God Object AntiPattern
Lets dip over to WikiPedia for the definition of a God
Object:
In object-oriented programming, a god object is an object that knows too much
or does too much… a program’s overall functionality is coded into a single
“all-knowing” object, which maintains most of the information about the entire
program and provides most of the methods for manipulating this data. Because
this object holds so much data and requires so many methods, its role in the
program becomes god-like (all-encompassing). Instead of program objects
communicating amongst themselves directly, the other objects within the
program rely on the god object for most of their information and interaction.
The God Object in CodeIgniter
CodeIgniter started as an early MVC framework that has maintained backwards
compatibility with PHP5.2. It’s maintainers have insisted on maintaining this
compatibility which has limited CI from taking advantage the advances that
PHP5.3, 5.4, and 5.5 introduced to the language.
There remains nothing truly wrong with PHP5.2. While 5.3+ offers us many great
advantages, a SOLID framework is still possible using the older version. CI’s
architectural issues do not stem necessarily from it’s usage of the older
version but rather the violation of SOLID principles in archetyping it’s
interpretation of MVC.
In CI we have the CI super class (the idea of a super class alone should be a
code smell) that is globally available via the get_instance() function. This
returns an instance of CI_Controller, our main application controller handling
the current request. This instance is our elusive beast. The God Object itself.
We’ll call this object CI from here on out.
In any one request there can be only one instance of CI – it is essentially a
singleton responsible for:
Loading models
Processing the request
Returning the response
Overloaded Models
Here is where we get into the meat and potatoes.
The CI object begins its life by loading resources, that is it begins by loading
various models and libraries and maintaining links to each of them like so:
This code instantiates an instance of the news model and assigns a reference to
news. It then instantiates an instance of events. In this manner every model
that comes into existence during request process is held as a reference by the
CI object and can be access latter on in the request, e.g.
Once more, something very peculiar is done during this process. CI not only
instantiates an instance of the given model but it also copies these
references to every subsequently loaded model.
Thus every object that is loaded in this manner becomes aware of every object
that had been loaded up-to that point regardless of whether that object really
needed access to the behaviors of those objects. The model becomes unnecessarily
bloated and the difficulty of debugging the behaviors of a given model
increases. Unintended behaviors might be caused not by the model itself but by
the combination of that particular model and the order or selection of
previously loaded models.
Examine a Model’s State? No way.
Take for example the simple act of using var_dump to see the state of an
object in memory. If we were to var_dump our instance of news we might as
well call it a day as news contains a reference to everything that has been
loaded into memory for our request. The server will proceed to dump the entirety
of our application to the screen for us to wade through!
No Public Property is Safe
A larger issue is the assigning of the references themselves. Since the first
act of initiating the model object is to copy CI’s massive registry of
references to the model any properties or references set in the model’s
constructor is at the mercy of the controller overwriting the model. Take for
example, the events model. Let’s say the following was in the constructor:
Following substantiation of the events object the Events object CI will
immediately overwrite the news property with it’s own instance of the news
property. Thus the events model would either need to make the news property
private or protected which would generate an error when CI attempts to
access it or we would always need to take care to keep our model properties from
existing in the same namespace as CI.
I actually ran into a horrible bug where this very thing happened. I had a class
named Validator that I loaded in with the controller. I also intended each of
my models to load their own instances of the Validator class and to initialize
their instances with own unique validation parameters. However, since the
controller had already loaded an instance of Validator it immediately
overwrote each of my model’s Validator’s forcing them all to use the same
instance of the class. The resolution to this problem was to have to name each
instance of Validator something different, thus we had EventValidator,
NewsValidator, etc.
I decided to share my fix for lightboxing in NextGEN Gallery 2.0.21. This
version of the WordPress plugin for some odd reason breaks support for
lightboxing the gallery images (that is having the gallery image “pop out” in
front of the page when clicked).
This fix does not modify the NextGEN gallery itself so we can easily revert to
using NextGEN’s lightboxing whenever it gets fixed.
Follow these steps:
1. Turn off NextGEN Lightbox Effect
Log into the dashboard of your WordPress installation and navigate to `Gallery
Other Options and select Lightbox Effects. There select from the drop down
No lightbox`
2. Install Lightbox 2 v2.6
It is important to have the most up-to-date version of Lightbox because of
compatiblity issues with jQuery 1.10. Go to the Lightbox 2
website and
download
the latest version of lightbox, unzip the download and upload the resulting
directory into your theme’s directory on your server (it should be in
/wp-content/themes/).
3. Update header.php To Load Lightbox 2
Now from the WordPress dashboard select Appearance >> Editor >> header.php.
For those of you without programming experience this might seem arcane but
follow along. Between the <head> and </head> tags include the following
lines of code:
Where THEME is the name of your current WordPress theme.
4. Add Custom Script to Your Footer
There is two ways of going about this. First navigate this time to `Apperance »
Editor » footer.php. We can either append the javascript directly to the end of
this file, or (the better solution) you could create an external javascript file
and load it.
To do the latter, you simply create a file named lightfix.js and paste the
script below minus the <script> and </script> tags. Then include it in your
file the same way that you included lightbox-2.6.min.js above only this time
append the include to the end of the footer.php.
If you want to just put the script directly in footer.php just copy the text
below directly into the file:
You might need to modify .storycontent img to fit your own theme. This script
selects all the img html elements in the div with a class name
storycontent it then loops through each of these images and if they are
contained inside an anchor tag then it transforms that image into a lightbox.
Since each picture in the NextGEN gallery is wrapped in an anchor tag linking to
the image source this should automatically work alongside Lightbox 2 to return
the lightbox functionality to our gallery.
I have a new post over on the Wind-Up Culture Blog concerning the the
extraordinary polish of Fez. Right now, I’m
at 82% of Fez completed and the game continues to blow my mind away with the
complexity of this indie title.
I just noticed today that a combination of the newest version of the
nextgen-gallery plugin with my custom jQuery and lightbox code succeeding
in completely breaking support of both such that neither the nextgen galleries
used in the Art and Photography sections nor the lightboxes used in various
blog posts really work.
If I have some time this weekend this will all be fixed up shortly.
Updated: The problem seems to be documented already with the 2.0.21 build of
NextGen. Since there is no fix for the problem and since I already have a
lightbox solution installed in the theme for automatically adding lightbox to
any non-lightboxed image in a post, I decide to just disable NextGen’s
implementation of lightbox and add a little javascript magic to solve the
problem.
I am struggling to find the words that adequately describe the simple joy that
is Fez. I think the word that I most often find in my
reflection is complete. That is, I think Fez is a more polished and “whole” game
than many a modern Triple-A title.
Concerning Publishing Unfinished Games
It has become too common to see games placed on shelves before they are truly
finished. I could point the finger at any number of triple A titles (mostly in
the MMORPG and FPS genres) wherein the release of the game is done before
production has really honestly finished. But the most brazen releasing of
unfinished games seems to come from the Independent scene where often games seem
more like tech demos then completed titles.
These unfinished games are hobbled together and released while their ideas are
still weak and unrealized. They lack the true polish that is necessary to fully
explore their game-play potential. Graphics are unpolished with no eye for
creating a cohesive aesthetic. Game-play consists of repeating the same simple
mechanic over and over. And content is either procedurally generated, random, or
simply lacking in complexity and attention to detail.
These poor unfortunate children are cast out into the marketplace and I am still
surprised to see so many titles getting praised despite their severe flaws.
Unity of Ideas in Fez
When I look at Fez what I see is a gestalt that creates an exceptional sense of
unity in presentation. The game is whole and explores its ideas sufficiently to
fully showcase the game without exhausting our temperament. I am reminded of the
original Super Mario Bros in that it is a game that could be beaten in a short
time but yet each piece – the art, the arrangement of the platforms, and
progressive difficulty was a creative expression that created an ensemble that
far exceeded it’s parts. Indeed, had one platform been off, had one level simply
felt as though it was a hap-hazardous assembly of ill thought ideas the entire
idea would collapse. But we do not see this with Fez, instead we see a kind of
excellence found only in minute attention to detail that encourages us to
immerse ourselves in the scene feeling secure that it will not disappoint us by
failing to reward our explorations.
In essence, we have a game whose levels encourage a kind of tranquil enjoyment
of each scene – the dog laying to sleep, the strange hieroglyphics adorning the
walls, and pixel-perfect skies. The developers behind Fez certainly felt the
need to reward such careful exploration as without the desire to wander about
the levels solving Fez’s mind-boggling puzzles becomes nigh impossible.
That is, the process of rewarding for exploration is built into the game. On one
level spinning a globe reveals hidden treasure maps. On another turning a valve
lowers and raises the water table on a completely different level. Puzzle pieces
reveal that what looks like decorative glyphs in the game may be a part of
solving a larger puzzle. Rather than punish us for wandering beyond the linear
paths and only rewarding us for progress, Fez rewards us for returning over and
over again to the same places to look again. Our approach to each level is
hyper-linear and this hyper-linearity creates a sense of choice not found more
linear narratives.
The Game-Play of Fez
The stages of Fez go on far beyond what I typically expect of an independently
produced title. We find such a variety of unique realms that rarely repeat their
themes – haunted mansions, seasides, jungles, and libraries.
Each stage reveals such a wealth of history into the eight and sixteen-bit eras.
We see tetris blocks built into the levels, Owls that look remarkably like those
found in Zelda, and a story that winks at the 2D “worlds” that exist inside our
computers as our hero sets off to save the world by collecting cubes all the
while electronic tears appear all about him in the world.
The idea of exploring a 3D world collapsed onto a 2D plane while still allowing
the user to change the plane of collapse is not a new one. Mario explored these
visuals in the various Paper Mario titles. Portal, likewise explores the bizarre
possibilities of physics-breaking that video game space can produce. So, like so
many other games before it, Fez is not something truly new but an exploration of
something that has come before.
But it is not the exploration of something new that makes Fez, or many great
games great. It is once again the fact that Fez is complete, polished and a
unified example of it’s kind.
Outside of a select handful of console titles that I absolutely adore (Zelda,
Mario, Shin Megami, Okami, Team Ico), most of my gaming goes on via the PC.
The Steam sales are thus regular points of interest in which I indulge myself in
buying far more games than I could realistically play through in a year.
To save myself from myself, I established a series of simple rules that I
(mostly adhere to) where Steam sales are concerned
I may only follow the summer sale.
I may only make one purchase per day.
So here’s my list of this year’s purchases:
The Witcher 2
Just Cause 2
Ys I & Ys II Chronicles
Borderlands 2
Torchlight III
Dust: An Elysian Tail
Civlization V Gold
Alan Wake Bundle
Baldur’s Gate: Enhanced Edition
Tomb Raider Collection
So there’s 10 purchases for 10 days! (Although Alan Wake gave me Alan Wake and
American Nightmare and Tomb Raider gave me the entire 10 game series).
A year ago, I promised a complete site overall. “It all has to go!” I said as I
started revising stylesheets and pulling apart templates.
Then suddenly, I took a year break from blogging.
The thing was, that as I started to revise the site I began to realize that the
whole thing lacked the certain kind of voice and insight that I had hoped to
achieve. It felt rather forced.
The site itself did not help much. The template was a kludge of spaghetti code
hammered together over a drunken weekend in college and looked nothing like the
simplicity of modern design. Indeed, the style-sheets were endless reams of
overrides and the Wordpress dashboard a mess of conflicting plugins.
I knew that I could do better, but I had no time for it. Disheartened, I stopped
blogging altogether.
It helped, that at the same time, there was a sudden rush of crunch time at
work, family weddings and holidays. My girlfriend getting a job first in Hulett,
Wyoming and then Ashton, Idaho. In all of this, I found myself back on the job
market trying to find a better position to cover the housing costs in what is a
rather expensive Midwestern city. I landed at
44Interactive who promptly put me to work as a
back-end web developer.
I found myself graduating from building modules for off-the-shelf CMSes (Joomla
and WordPress) and into the realm of MVC frameworks and Dev-Ops. I took up the
reins of Systems Administrator, switching my OS to Ubuntu, cracking my head
against the Linux Documentation Library and straightening out a series of
complex system of servers that had grown organically for far too long. I set up
PCI compliant production servers, I created Dev servers for users to work off,
and mastered working off a local LAMP stack and organizing my GIT flow to
integrate into the new teams work.
Meanwhile, I spent my weekends driving through each of South Dakota’s winter
storms to see Jess and then into the Spring and Summer making the longer commute
to telework from Idaho. Even today, I am moving piecemeal out to the
Caribou-Targhee area were I will be permanently teleworking from now on.
Through all of this, I felt like I had no time to write, no time to draw. But
then this last month, I picked up my pens and realized how very much I missed
them and the tranquility of sitting down to simply create.
The New Sites
The site you see comprises my last two years of professional growth. A new
modern design emphasizing a better typography, white-space and subtleties in a
well structured Word Press template. All the articles have converted to
markdown in order to give them a
uniform look and to escape from the trap of trying to design new layouts for
each article. Comments now use the Disqus system to provide
single authentication logins and to hopefully encourage greater user interaction
– which until now has been mostly non-existent.
My hosting has also moved. I am putting my Linux administration to good use and
hosting this off my own personal VPS provided by Digital Ocean.
Kynda.net now serves as my primary host managed 100% by
yours truly. The bowlich.com domain is now retired with my
existing and future projects ( Dreamscapes and
The Wind Up Blog moved to subdomains of our new
host.
Likewise, The Wind-Up Bird features the same template and markdown improvements
as my main blog and Dreamscapes will be ported to a custom
Silex CMS whose design I plain to layout over
the next few months.
To the right, you will find links to my
LinkedIn
profile and Bitbucket accounts, the latter
which I hope to begin slowly incorporating new OSS projects.
Expect a complete overhaul of this site’s pages, and a return to regular
articles. Particularly, I hope to address Javascript architecture, the pitfalls
of Code Igniter, tips for administering CentOS/Ubuntu servers, a series of
articles laying out how to quickly mock up a simple CMS using Silex, and my
adventures exploring independent game development using the PyGame and PyGlet
frameworks for Python.
It has been almost one year exactly since I posted my progress in attending the
life studies group in Sioux Falls. I did not attend nearly as much as I had
hoped last year. Indeed, with heavy overtime through the fall and only a
scattering of visits last winter followed by an outright abstinence through the
spring and into early summer – I am surprised that I have this many sketches to
scrap up and post.