on Tutorials

CakePHP from Scratch: Theming in real life example – Part one

14 comments
f-css-01
Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

As I already explained, we are going to build a jobs board application using CakePHP. If you followed our previous tutorials, you should already have a full working application. It is currently in default CakePHP look and feel. Today, we are going to change that and apply the free template from the internet.

Second task is to separate that template and make a theme, so in the future, we can just replace the design, and change the theme. It is similar to WordPress themes.

I downloaded a simple template from Template Kingdom and it looks like this:

As you can see, the template has more stuff then we need, but we will deal with this as we go along with our application.

From now on, I will make everything by hand and will not use the Bake command prompt tool. The goal is to show the whole code and the process, so you can learn as much as possible about CakePHP and what is going on under the hood.

So, first, download the template from here (or use your own template, it will be even more interesting).

There is a PSD file included and please read the included license file carefully if you plan on using this theme!

In order to make a theme, you will need to create the folders that will hold the theme files. Go to /app/views and create a new folder named themed. Inside that folder, create a folder named default. This will hold our theme files. Now, copy all the folders and files from /app/views to /app/views/themed/default folder.

Our CSS and Javascript files will be stored in /app/views/themed/default/webroot folder, so please create it. Inside the new created folder, create folders css, img and js. Copy the CSS files from the downloaded template to /app/views/themed/default/webroot/css folder and rename the style.css to default.css. Copy the images folder to /app/views/themed/default/webroot/img. Now, open your CSS file and change the paths to images to ../img so it can find them.

Now, let’s go and open the /app/views/themed/default/layouts/ and copy the index.html file from downloaded template and paste it here. In order to make a layout for for our theme, rename it to default.ctp.

I personally like to put .ctp extension to be recognized as PHP files in my editor, so the syntax highlighting work.

Ware done with preliminary work for theming. Now, we need to tell CakePHP that we want to use the Theme features and what is the name of our theme. As we will be using the same theme all over our application, the best place to do it is in our app_controller. App controller is a class that extends the basic CakePHP Controller class and is called in every controller.

So go ahead and create /app/app_controller.php and paste in this code:

class AppController extends Controller {
    public $view   = 'Theme';
    public $theme = 'default';
}

This way we are overriding the default View class for every controller and telling the engine to use Theme class. At the same time, we are telling CakePHP that our theme is called default.

Now, CakePHP is looking at our newly created folders for our theme.

If a view file can’t be found in the theme, CakePHP will try to locate the view file in the /app/views/ folder. This way, you can create master view files and simply override them on a case-by-case basis within your theme folder.

Now, point your browser to http://localhost/cake/ (or wherever your application resides) and you should see that this is working. You have got HTML from the downloaded templates without implemented styles.

If you comment out the two lines we just added in our app_controller.php file and refresh the browser, you should see default CakePHP template. OK, uncomment the lines and let’s get that CSS fixed.

If you are wondering why the CSS is not working, it is because the path to the CSS file is wrong. So, open up your /app/views/themed/default/layouts/default.ctp file. This is our layout for the application. You can create as many layouts as you wish: just place them in the app/views/layouts directory (or /app/views/themed/layouts if you are using themes), and switch between them inside of your controller actions using the controller’s $layout variable, or setLayout() function.

CakePHP features two core layouts (besides CakePHP’s default layout) you can use in your own application: ajax and flash. The Ajax layout is handy for crafting Ajax responses – it’s an empty layout (most ajax calls only require a bit of markup in return, rather than a fully-rendered interface). The flash layout is used for messages shown by the controllers flash() method.

Three other layouts xml, js, and rss exist in the core for a quick and easy way to serve up content that isn’t text/html.

But let’s get to work. First change your character set to this:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

We will work our way from up to bottom. First, we need to make our titles dynamic. SO change your title tag to this:

<title><?php echo $title_for_layout; ?></title>

$title_for_layout will hold the Page title. Now replace the CSS tag to this line to connect the correct path to CSS:

<?php echo $this->Html->css('default'); ?>

Now, refresh the page and you should see that CakePHP has correctly rendered our layouts and use themed CSS. Notice that the images are not working as they are on the wrong path. But, this is something we will deal with in the next tutorial.

Let’s go on. I will correct the logo image, so it will look nicer and you can see how it is done. Find this line:


and change it to:

echo $html->link($html->image("logo.gif"), array('controller'=>'jobs', 'action' => 'index'), array('escape' => false));

Refresh your page and the logo appears leading to your home page controller.

Now, we will move our menu out of default.ctp and create a new element out of it. This way, we can change it in one place and the changes will be visible to our whole application.

Cut this code:

<!--Navigation Background Part Starts -->
<div id="navigation-bg">
	<!--Navigation Part Starts -->
	<div id="navigation">
		<ul class="mainMenu">
			<li><a href="#" class="selectMenu" title="Home">Home</a></li>
			<li><a href="#" title="About">About</a></li>
			<li><a href="#" title="Services">Services</a></li>
			<li><a href="#" title="Support">Support</a></li>
			<li><a href="#" title="Chat">Chat</a></li>
			<li><a href="#" title="History">History</a></li>
			<li class="noBg"><a href="#" title="Contact">Contact</a></li>
		</ul>
		<a href="#" class="signup" title="signup now"></a>
		<br class="spacer" />
		<!-- <ul class="subNav">
			<li class="noBg"><a href="#" title="Our Benefits">Our Benefits</a></li>
			<li><a href="#" title="What Our Future Plans">What Our Future Plans</a></li>
			<li><a href="#" title="Our Success">Our Success</a></li>
			<li><a href="#" title="Ratings">Ratings</a></li>
			<li><a href="#" title="Latest Blogs">Latest Blogs</a></li>
			<li><a href="#" title="News">News</a></li>
			<li><a href="#" title="Testimonials">Testimonials</a></li>
			<li><a href="#" title="Comments">Comments</a></li>
		</ul> -->
		<br class="spacer" />
	</div>
	<!--Navigation Part Ends -->
</div>
<!--Navigation Background Part Ends -->

Create file menu.ctp in /app/views/themed/default/elements, copy the menu code in it. Paste this on the place where menu was in default.ctp:

<?php echo $this->element('menu', array('cache' => true)); ?>

The cache part is telling CakePHP engine that we want to cache this element. This is great, as it almost never changes.

Now, let’s adjust our menu to work better:

<!--Navigation Background Part Starts -->
<div id="navigation-bg">
    <!--Navigation Part Starts -->
    <div id="navigation">
        <ul class="mainMenu">
            <li><?php echo $html->link('Home', array('controller'=>'jobs', 'action' => 'index'));?></li>
            <li><?php echo $html->link('Categories', array('controller'=>'categories', 'action' => 'index'));?></li>
            <li><?php echo $html->link('Users', array('controller'=>'users', 'action' => 'index'));?></li>
        </ul>
        <a href="#" class="signup" title="signup now"></a>
    </div>
    <!--Navigation Part Ends -->
</div>
<!--Navigation Background Part Ends -->

This is how our menu looks now. I removed the submenu part, as we will not need it for the moment. If refresh the page, you will see that nothing changed. That is because we told CakePHP to cache the element, and now we have to go to /app/tmp/cache/views and delete the cache file (it is called element__menu). Refresh the page and our menu is working like charm.

The last and most important part is to include our actual views into our layout. Find all this code and remove it:

<!--Our Company Left Part Starts -->
		<div id="ourCompany-leftPart">
			<h2 class="faq-Hdr">Latest F.A.Q?s</h2>
			<ul class="ourCompany-list">
				<li>Nulla congue pretium elit. Integer enim risus, mollis.</li>
				<li>Eget, accumsan id, feugiat eu, velit. Sed molestie.</li>
				<li>lectus id nisi.</li>
			</ul>
			<h2 class="moreIdeas-Hdr">More Ideas About Us</h2>
			<ul class="ourCompany-list noBottomPadding">
				<li>Quisque laoreet, elit at tincidunt porta, massa torr.</li>
				<li>Porttitor magna, at vehicula pede dui id enim.</li>
				<li>Pellentesque rhoncus metus quis nulla. Donecllus.</li>
				<li>Metus, vehicula nec, scelerisque commodo.</li>
				<li>Egestas eget.</li>
			</ul>
		</div>
		<!--Our Company Left Part Ends -->
		<!--Our Company Right Part Starts -->
		<div id="ourCompany-rightPart">
			<h2 class="moreInfo-Hdr">More Informations</h2>
			<ul class="ourCompany-list noBottomPadding">
				<li><a href="#">Aenean viverra sapien a enim pellentesque</a></li>
			</ul>
			<p class="moreInfo-Text">Pellentesque id nunc at leo<br />
			vestibulum lobortis</p>
			<h2 class="searchUrl-Hdr">Search Our Url's</h2>
			<ul class="ourCompany-list noBottomPadding">
				<li><a href="#">www.,elit at tincidunt/porta.com</a></li>
				<li><a href="#">www.vehicula pede /a/dui id enim.com</a></li>
				<li><a href="#">www. quis nulla.com</a></li>
				<li><a href="#">www.scelerisque commodo.com</a></li>
			</ul>
		</div>
		<!--Our Company Right Part Ends -->

And add this to its place:

<?php echo $content_for_layout; ?>

And change the h2 above it to:

<h2 class="ourCompany-hdr"><?php echo $title_for_layout; ?></h2>

Refresh the page in browser and click on the links in menu. Our application is not looking good but is fully working in our new theme.


That is it for the part one, in part two we will write a little bit of CSS to repair the layout and add some things that we will need. So stay tuned.

Make sure your read our previous tutorials in CakePHP series:

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon



  • Mike

    Very nice introduction into CakePHP theming.
    Keep it up!

  • Don

    Looking forward to part 2….

  • Pingback: Tweets that mention CakePHP from Scratch: Theming in real life example – Part one | CodeForest -- Topsy.com

  • Mohamed Zeid

    Really amazing; simple and to the point.

  • Paul

    Cool tutorial, i’m going to go back and find your initial CakePHP tutorial and start from the beginning. Would you recommend CakePHP to a PHP beginner or is it a more advanced framework?

    • Zvonko

      It is a bit advanced, but when you catch up, it will save plenty of time.

  • Mohamed Zeid

    Hi Zvonko,

    Sorry to post this here, but I could not find another way to contact you. I thought you might be interested into this.

    I thought you might be interested into this.

    http://www.cakepower.org/

    CakePOWER works as a software layer between CakePHP and your application and provide some advanced behaviors to CakePHP framework:

    * url embedded lang request
    * drop-in plugin support
    * cross-plugin interoperation
    * you can add methods to controllers, models, components, helpers with a non-hard-code approach
    * auto compression of js and css

    Wiki page:

    http://www.cakepower.org/wiki/doku.php

    I have nothing to do with this project, but I thought you and our fellow cakebakers might be interested into it.

  • Tom

    can you also explain later how can this jobs board be localized – into another language ,

    or how to make it a multi-language board

    • Zvonko

      Of course, I will do that.

  • Pingback: CakePHP from Scratch: Theming in real life example – Part Two

  • Harish

    This is a very nice tutorial on themes. Just a small correction, the folders for CSS, img and JS are wrongly mentioned. They should be under /app/webroots/themed/default

    • Zvonko

      No. As of CakePHP 1.3 the new path for themed CSS, JS and img folders is /app/views/themed/webroot

  • Mike

    These are without a doubt the best Cake tutorials I have come across, please don’t stop writing them.

  • http://elogicsoft.com Elogicsoft

    This is perhaps the best CakePHP tutorial i have ever gone through. I have learned some thing about CakePHP. I have downloaded the rar you have attached here. This is quite good – but one thing i could not able to integrate this in CakePHP 2.0. Can you pls write another tutorial how to do this. Thanks you in advance. And Thank you very much for your time as well.

    Regards,
    Elogicsoft