First Steps with CakePHP

Starting a new, personal project in PHP, I wanted to try out a new framework for the fun of it. After doing a bit of review on many available frameworks, and ruling out the ones I have already used (Zend and OpenAvanti), I settled on CakePHP.

CakePHP
CakePHP

Installation and basic setup were a breeze, and I found the online documentation and tutorials helpful. Very early on, however, as I thought I was still trying to accomplish basic site setup tasks, I began to run into a few road blocks. Luckily, the API documentation is quite thorough and a pleasure to read, so I eventually got through the initial “new framework pains”. In this post, I will walk you through my basic setup and hopefully answer a few questions that may pop up for you after those initial inquiries into the docs.

Here is what I wanted to accomplish (This example isn’t meant to showcase fantastic architecture. It’s just to serve the purpose of making sure I knew how Cake was going to handle things. And believe me, it took several tries):

  • Have a public home page with a link to the admin panel
  • The admin panel requires user login

Simple, right? So let’s get started. Note that I’m using CakePHP 2.0.

The first thing we want to do is tell Cake that we intend to use the built-in Authorization Component. I chose to do that in the AppController, so that it is available to all controllers. Copy the default AppController file from the lib/Cake/Controller folder into the app/Controller folder. Within the class declaration, add the following code:

var $components = array('Auth', 'Session');

The $components variable takes an array of components, one of which we’ve specified as Auth.

Next we want the site to use our home controller as the default. Cake comes pre-built to use the pages controller, specified in the app/Config/routes.php file:

	Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));

We are going to change this to:

	Router::connect('/', array('controller' => 'home', 'action' => 'index'));

Now that we are setup to view home/index once we navigate to our site, let’s define the home controller in app/Controller/home_controller.php:

class HomeController extends AppController {
	var $uses = null;

	function beforeFilter() {	
		$this->Auth->allow( 'index' );
	}

	function index() {
	}
}

Since the Auth component is in force for all controllers, we need to tell it to relax for the home/index action. We do this with the beforeFilter() function.

Also note the setting of $uses to null. Controllers usually have this set to the table they will be referencing. In this case, it makes no sense to have a “home” table in the database, so we must tell the controller that we are not going to be using a table.

Now we just need a view to show our admin panel link (located in app/View/home/index.ctp):

<p>This is the home/index view</p>
<p>
	<a href="/admin">Admin Panel</a>	
</p>

If you navigate to your site, you should see the admin panel link.

Home Page
Home Page

What we want to happen here is for a login screen to display if the anonymous user clicks the admin panel link. We’ve already told Cake that we are using Auth. Now we just have to do a couple of things to hook up a login screen and authenticate a user.

First, Auth is expecting a users controller (app/controller/users_controller.php):

class UsersController extends AppController {
	var $name = 'Users';

	function login() {
		if ($this->request->is('post')) {
			if ($this->Auth->login()) {
				return $this->redirect($this->Auth->redirect());
			}
			else {
				$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
			}
		}
	}

	function logout() {
		$this->redirect( $this->Auth->logout() );
	}
}

Setup the login view (app/View/users/login.ctp):

 echo $this->Session->flash( 'Auth' ); 
 echo $this->Form->create( 'User' );
 echo $this->Form->input( 'username' );
 echo $this->Form->input( 'password' );
 echo $this->Form->end( 'Login' );

Note: To insert a password into your database that can use for login, use Cake’s built-in AuthComponent::password(‘your_password’) function to determine the hash.

Let’s setup the admin panel. Create the admin controller (app/Controller/admin_controller.php):

class AdminController extends AppController {
	var $uses = null;

	function index() {		
	}
}

And the view (app/View/admin/index.ctp):

<p>This is the admin panel</p>

Now if you click the admin panel link on the home page, you should be greeted by a login screen.

Login Screen
Login Screen

After a successful login, you should then see the admin panel.

Admin Panel
Admin Panel

So that is how I got a very basic setup running with CakePHP. Check out the great documentation at the official site if you run into trouble, and even start browsing the API. It’s good stuff.

Learning Has Always Been Fun

Learning is Fun

I was reading a blog post today about how a few companies are collaborating on a new app for NASA that will integrate the playability of an MMORPG and the coolness of real-world science. This sounds incredible to me and I can’t wait to try it. The one thing that irked me though was how when things like this come up, the cliche thing for marketers, journalists and the media to say is, “it will make learning fun” or “your kids won’t even know they are learning”.

News flash to those out there that think you have to disguise learning: LEARNING HAS ALWAYS BEEN FUN AND PEOPLE ENJOY IT.

With few exceptions, everyone loves to learn. Learning new things is what makes life exciting instead of the same old thing everyday. Talk to almost any kid in elementary school and they enjoy going to school and absorbing loads of new information. Post-elementary? Well, that’s where the excitement begins to diminish. Why?

That brings me to my theory of where this popular “It’s OK, they won’t know they’re learning” phrase came from. It probably stems from many kids’ attitudes toward post-elementary school. Learning isn’t a drag, school is. Allow me to elaborate.

The School Setting

Do you remember what it was like walking into your elementary school classrooms? I remember there were heavily decorated walls. Posters of planets, ecosystems, history and far-off places invigorated the mind. Art projects hung from the ceiling. Who wouldn’t get excited to dive into knowledge in a setting such as this? These are the best years of school.

This week we took our kids to their school open houses. As expected, the classrooms for our two youngest in elementary school were comfortable, full of creative inspiration and poised to take in a roomful of energetic kids. Then came the middle school for our two oldest kids. What did those classrooms feel like? In a word, boring. White cinder-block walls. One or two posters. Nothing hanging from the ceiling. Desks in rigid rows. Cold and sterile. Wow. Let’s open up that social studies book and have fun!

Why can’t we carry that “elementary school room” mentality throughout middle school, high school and beyond? Do we think decorations and models are childish? I don’t understand. Why is it that the system thinks we don’t need to be fully stimulated anymore as we grow older?

Following the Rules

One of my most negative memories of school was during a high school English class where we were given a short story writing assignment. At that time I had a favorite author who I liked to emulate. One of his popular writing techniques was to end a paragraph with a very short “sentence” for impact. For example, the end of the paragraph might read, “Very cold.” Now, you know and I know that this is not a complete sentence in the sacred, formal rules of grammar. So what? I loved how it sounded and how it made me feel when I read it (I actually used a few in this post, ahem).

“No. That is not allowed. I’m marking points off”, was the teacher’s response. That’s interesting. I wonder if the author, who made millions of dollars from his books writing that way, realized his blatant disregard of the English language with his sentence fragments?

My point is that creativity is stifled when students aren’t allowed to push boundaries and bend rules. Isn’t history full of examples of greatness when so called “rules” are not followed precisely?

Sark feels my pain in her book, A Creative Companion.

At school, things may have changed. The chairs were in rows, and tree trunks were to be colored brown, not purple. If you lived in a world of purple tree trunks, you probably learned to hide it.

Encourage Learning. Encourage Fun.

Our education system should do everything it can to keep our students excited for the long term. I think two very simple steps could be taken right now. Make the school settings engaging throughout all levels of education and encourage creativity and rule bending.

Learning is not a drag. School is. Let’s change that.