Mobile browser detection and optimization in CakePHP Made Simple

Here is a helpful guide I found while learning to work with JQuery mobile and CakePHP together to create a mobile version of one of my websites.

Hope the line below make sense to you, if not feel free to ask questions in your comments. Here we go …

I needed to do two things:

Detect webkit-based mobile browsers

Automatically serve those browsers a mobile optimized page if one was available for the requested action.

Here’s how I did it, and how you might, too.

Step 1: Update Cake’s browser detection to include Android devices

Cake’s RequestHandler component includes a nifty method for detecting mobile browsers — $this->RequestHandler->isMobile() — but the default list of devices detected by Cake 1.2 is a bit dated.

Fortunately, it’s easy to update. The default list of device names is found in the RequestHandler component’s core file, cake/libs/controller/components/request_handler.php:

if (!defined(‘REQUEST_MOBILE_UA’)) {

define(‘REQUEST_MOBILE_UA’, ‘(iPhone|MIDP|AvantGo|BlackBerry|J2ME|Opera Mini|DoCoMo|NetFront|Nokia|PalmOS|PalmSource|portalmmm|Plucker|ReqwirelessWeb|SonyEricsson|Symbian|UP\.Browser|Windows CE|Xiino)’);

}

Update this by copying it to your core configuration file — /app/config/core.php — and adding the device names of your choice. I simply added Android to snag all those new Google-happy devices using webkit browsers. To wit:

define(‘REQUEST_MOBILE_UA’, ‘(Android|iPhone|MIDP|AvantGo|BlackBerry|J2ME|Opera Mini|DoCoMo|NetFront|Nokia|PalmOS|PalmSource|portalmmm|Plucker|ReqwirelessWeb|SonyEricsson|Symbian|UP\.Browser|Windows CE|Xiino)’);

Step 2. Decide where to put your mobile views

There are several places you could put mobile view files — app/views/elements or app/views/themed come to mind — but I decided on something slightly different. Cake automatically looks for an action’s view files inside a view folder named after the action’s controller. For instance, a page request for users/login expects to find a view file at /app/views/users/login.ctp. Given that, I extended the convention by creating a subfolder named mobile inside each controller’s existing view folder. So, my mobile view for users/login is located at /app/views/users/mobile/login.ctp.

Step 3. Create a mobile layout file

Mobile-optimized pages will need a different layout than standard pages. Create a file named mobile.ctp and save it inside /app/views/layouts.

Step 4. Create the logic for detection and view setting

Here’s where Cake really shines. All we need to do in order to send all mobile devices to any mobile-optimized pages is create the following logic inside the beforeFilter() of /app/app_controller.php.

// check for mobile devices

if ($this->RequestHandler->isMobile()) {

// if device is mobile, change layout to mobile

$this->layout = ‘mobile’;

// and if a mobile view file has been created for the action, serve it instead of the default view file

$mobileViewFile = VIEWS . strtolower($this->params[‘controller’]) . ‘/mobile/’ . $this->params[‘action’] . ‘.ctp’;

if (file_exists($mobileViewFile)) {

$mobileView = strtolower($this->params[‘controller’]) . ‘/mobile/’;

$this->viewPath = $mobileView;

}

}

This code does the following:

Detects mobile browsers using our updated device list

Changes the layout to our new mobile layout

Checks to see if a mobile view file exists inside the mobile subfolder described above.

If the file exists, the logic changes to the mobile view before displaying the page.

One thing to keep in mind about this approach is that it doesn’t allow mobile viewers to switch back to the standard browser view, assuming instead that you’ll take care to retain all essential functions in your mobile views. It does, however, preserve your original URLs across all platforms, with none of that ganky mobile redirection that lesser sites use.

via Mobile browser detection and optimization in CakePHP 1.2 • Made Thing.

The New Etisalat Free Internet browsing Tweak

A few days ago, I saw a thank you message in my mailbox from a faithful reader on how he’s been able to browse free with his Etisalat SIM after our last chat. His reaction went like this;

…good evening Mr Ahmsta… I have good news for you…. After the last mail I sent to you, then the next day my MTN BB subscription expired. Then I just made up my mind to use Etisalat for a trial. I started with daily BB subscription for N100. Then I inserted the exact settings as you posted for MTN. But surprisingly after my subscription expired, I could still browse, free of charge. I am still using it. Oga you really tried a lot… I can’t say it’s my work but it’s your words of encouragement that made me win, cos if you could remember when I asked you if the settings would work for other networks you said its only tested on MTN, but believed it would also work for the other networks…

Thanks my oga, God bless. 1love!!!!!!

Real good news, isn’t it? Well I thought of getting the full details on how he did it because I have limited time in testing and yes… It’s just the same as I posted previously, in other not to waste much time talking about stuff behind let me go straight away to how he was able to do it

How To Setup The New Etisalat Free browsing.

First all you have to do like he said above is to recharge a N100 on your mobile,

After that, then you need to subscribe for the etisalat internet blackberry plan by dailing *499*3*2#, Few minutes after that yo will get an SMS message like the following:

Welcome to the Etisalat blackberry Complete voice plan.

That’s all you’ll need. Restart your mobile then configure your gadgets like this

Mobile

Connection name : Ahmsta Connection

Data Bearer: Packet data

Access point name: blackberry.net

Username & Password : web

Authentication: Normal

Homepage: http://www.ahmsta.com

After filling those, then click option >> Advance settings

Network type : IPv4

Phone IP address : automatic

DNS adress: (primary: 8.8.8.8, then secondary: 8.8.8.8)

Proxy Server Address: 10.71.170.5

Port: 8080

For your computer just configure your browsers / applications to use you can use the same configure for the MTN Bis or rather use this

Access point – blackberry.net

Click Advance and set your DNS as follows

DNS address: (primary: 8.8.8.8, then secondary: 8.8.8.8)

Proxy address:- 10.71.170.5

Port:- 8080

That’s all,

In this case, Ultrasurf is not really needed, but if you still use it, it will sure work

NOTE: Its likely you get billed if you recharge while using this, so its better you opt out before you recharge your account.

Thanks to you Nibras Muhammad.

via browsing Tweak.

How To Build a Game In A Week From Scratch With No Budget

Champions (role-playing game)

Champions (role-playing game) (Photo credit: Wikipedia)

Here is an interesting read about how this dude built a game in 40 work hours without a budget.

I’m sure you can gain some inspiration from this story as you think of embarking on your next game project.

An RPG in a week, starting from scratch? How hard could it be?

I did it because of a dare.

There are many great resources available to small, budget-conscious independent game developers today. On a public forum, in a counter-rant, I expressed this fact by bragging that if you gave me a week, a fresh install of Windows, and a good Internet connection, I could build a halfway decent game with no budget whatsoever. No, it wouldn’t be able to compete with Halo 2 or anything (if I could create that kind of game in a week, I’d quit my day job), but it would be reasonably amusing and playable.

Tom Bampton, who runs the monthly Game-In-A-Day ‘competition’ (www.gameinaday.com ), said “You’re on!” He then added an extra contingency – I had to do it without the benefit of one of the (free) game engines out there. I could only use a basic library / API.

At first, I dismissed the idea. I didn’t have time to take a week off of work and my current game development project to do something like this. But then I thought: What is a week? Unless you work for EA, a work-week is 40 hours. How about taking 40 hours to create a game? I was intrigued – but I didn’t want to just create a space-invaders clone. How about a role-playing game – one of the most complicated genres to create games for? Would it be possible?

I didn’t know. I knew it would be extremely difficult. But I accepted the challenge.

On top of that, I documented what I was doing as I worked, which I expected would be a little like going through an entire development cycle on fast-forward. I thought it might be interesting to game developers – or at least an entertaining record of how I fell on my face if I failed. The end result was a long, rambling, stream-of-consciousness record of my hourly activities. I’ve tried to edit it down to something a little less yawn-inducing here.

So here is how I created a game in a single week from scratch, with no budget. If you want to skip to the end and see what the final product looked like, in all it’s buggy, imperfectly-realized glory, you can download the Windows version of the game at: http://www.rampantga…ackenslash.html

The Plan

The Goal

Create an “old-school” RPG in the style of the old, early 80’s “top-down” RPGs like The Temple of Apshai, Ultima III, and Telengard. The player will move through rooms in a stereotypical dungeon, doing battle with various monsters with magic and combat. Along the way he’ll improve his capabilities through gaining “levels” of experience, and magical equipment.

It won’t all be about combat, however. The player will also have the ability to sneak past or negotiate with monsters. There will be locked and trapped doors and chests, and unique dungeon features that may have strange effects. The game will not be long on plot, characterization, or dialog – it’s mainly a hack & slash affair. You go up the level treadmill until you are powerful enough to face the final boss, retrieve a great quest item, and bring it back safely home (your ‘starting room’).

The Rules

Rule #1: A limit of one work-week (defined as 40 hours)
Game Development time should be restricted to 40 total hours. These will be actual game development or research hours. Breaks of longer than ten minutes won’t count towards the total time. This will be an “ideal” workweek of 40 highly productive hours.

The 40 hours only includes development to a feature-complete “alpha test” stage. Debugging and packaging the game for distribution and won’t count towards the development time, but no new features should be implemented. Documentation of the process doesn’t count.

Rule #2: All Free Tools
Except for the software that comes with a Windows install, only free / open-source software tools are used. The point of this whole exercise is to show how you don’t need expensive (or even not-so-expensive) tools to develop a game. Hardware such as a scanner, microphone, and digital camera are exempted from this rule – if you don’t have these, you can probably borrow them from someone.

Rule #3: No Engines, only basic libraries / APIs
The game must be created “from scratch” without the benefit of a fully-featured Game Engine. No cheating and creating a game using some kind of “click-and-play” game-maker software to throw together a game.

The Tools

Code:

Art:

Sound:

The (Intended) Schedule

Schedules are made to be broken, but it’s important to have them as a baseline to compare your progress with and make corrections as necessary.

Hour 1-10: Basic Architecture
Design the “engine” and the main components. Get the world displaying on the screen. I should be able to move a ‘test player’ around the world to look at things. In fact, I should allow the “test player” to be turned into a full-on editing tool if I can swing it.

Hour 11-20: Player Interaction
Implement all core interactivity for the player – moving around, attacking things, opening doors, dying, picking up and using inventory. Bare-Bones representative objects in the environment will be created to test the interactivity

Hour 21-30: Making the World Active
Add the AI, game “events”, traps, and special effects. By the end of this period, the game should be a pretty complete tech-demo of all of the game’s major features.

Hour 31-40: Adding Content and Rules
Take the project from “tech demo” to game. Add all additional content. Complete and balance the game-play mechanics. Apply polish where time permits – adding special effects, animation, etc.

Post-Hour 40: Testing and Game Release
Fix bugs (no adding features!) Package up the game and release it. Finish documentation.

The Development Diary of Hackenslash: A Game In A Week

Hour 1 – Wild Freeform Design and Base Classes

I spend this hour creating some basic classes for the game – and using these to help guide my design. The world is represented as a series of rooms, connected by portals. Everything in the world is room-relative, similar to how old Adventures and MUDs are designed. Most objects in the game are represented by a “GameObject,” which has a position and contents (which include other objects – a map might contain rooms, a room contains a box, a box contains a sword… and I guess the sword could contain more rooms, but we won’t go there.)

  • I create a “creature” and “player” object
  • I generate a set of “attributes” off the top of my head for creatures, and put this in a class. Apparently I’m a game geek who has played way too many RPGs. I don’t know exactly how the game mechanics will work, yet. This really is seat-of-the-pants game development!
  • I make a “room” object, derived from GameObject. Rooms have width, height, and walls – and not much else right now.

I figure out how things will work and make corrections as I go. I don’t even have PyGame linked in at this point – I don’t even have anything other than a console for output. But I feel like I’ve made great progress!

Hour 2 – PyGame 101

The goal this hour is to initialize PyGame, and start putting things on the screen. Actually, I spend most of my time going through the PyGame documentation and figuring out how to do things, since I have almost no experience with PyGame or SDL.

I end the hour bringing up a blank screen filled with black. So far, it’s not very impressive. Actually, there’s quite a bit going on behind that black window – sort of like the Black Triangle story. There’s a functional game-loop, page-flipping, the calling of several classes, and a lot of stubbed behavior. But that doesn’t make the black screen any more impressive.

Hour 3 – If the Walls had Ears, I’d be cussing at them

This hour’s goal is to get a room’s walls displaying on that black screen. To make this happen, I need a room, and I need graphics. I spend a lot of time in GiMP touching up some textures downloaded from Mayang’s Free Textures, so that they tile. I create a texture manager class. And I fill out a sample room structure. I also spend a bit more time looking through PyGame’s docs to see if there’s anything else I can use that might make the job easier.

At the end of the hour, I still don’t have walls on the screen.

Hour 4 – The Inn Now Has Room

After fighting some syntax errors, I finally get the walls to appear on screen. Not displaying correctly – they are in the wrong positions, with gaps between segments. It’s horrible. But with a little bit of tweaking and bug-fixing, I have something resembling a 10-square by 10-square room on the screen.

via GameDev.net.

Struggling with getting things done? Why Not Take Some Time to Understand The Power of Vision.

While doing some research 0n game development I stumbled on this article and although it seems to have almost nothing to do with actual game development, I picked out something very essential from it.

This has to do with our responses to challenges in life. Like if you wanted to go about creating a new game that would be a world changer, you need to set out with the right mindset.

Here’s is the most important part of this story with a link to the full story at the end.

The lessons I learned that day are ones that I would like to apply more often in my life. When I do remember them, they serve me well. Based on this (and other) experiences, I extrapolated the following lessons which have proven useful to me in more than just gymnastics:

#1 – Make sure you have a clear and CORRECT vision of your goal. Your body, mind, and spirit will do all kinds of work underneath your consciousness to help you achieve those kinds of goals. But if your goals are vague or flawed, you will get a confused or flawed result.

#2 – A detailed goal is helpful, but not necessary (beyond helping you achieve that clarity). After all, envisioning all those details about the movement of my body and arms to improve my rotation only helped me incrementally. But when I got the final version of my goal right, my body and mind already KNEW subconsciously what to do. I suspect that if your vision is TOO overburdened with details, it will lose clarity. Better to focus on the important parts and critical details, and let the rest take care of themselves.

#3 – Regularly re-focus on your goal! In the example, I would envision the whole thing in my head each and every time before I made my attempt. When you run a real risk of breaking your neck on a critical failure, this kind of discipline comes easy. So I’d envision it dozens of times a day.

#4 – Measure, evaluate your progress, and make corrections to your goal / vision as necessary. I doubt I’d have succeeded on my first try even if I had the perfect vision to begin with. But at the end, I was actually much closer than I thought, and I only needed to make one minor amendment to my vision to succeed (and, in fact, go too far).

#5 – Don’t be afraid to ask for outside help, observation, and guidance. Just remember that they can’t / won’t do it for you – success still has to originate from within yourself.

via Tales of the Rampant Coyote: The Power of Vision.

Javascript JQuery var $varname is not a PHP variable!

JQuery

JQuery (Photo credit: Wikipedia)

Recently, I came across some JQuery code with a variable declaration having a $ sign before the variable name.

Below is an excerpt of the code.

var markup = "<p>" + category.description + "</p><ul data-role='listview' data-inset='true'>",
$header = $page.children( ":jqmData(role=header)" ),
markup += "</ul>";

After doing a brief search I found the following explanation very useful and this might take out the confusion that may have you screaming to yourself “Is JQuery now running PHP?”

“ It just seems to be common practice by a lot of jQuery people smarter than us to signify it’s a jQuery object stored in that variable, it has zero to do with jQuery itself per se”.

via [jQuery] var $varname – jQuery Forum.

What Exactly is this JQuery Mobile that they use for Mobile Application Development?

I have been doing normal html, and interactive websites/ web apps using PHP/MySql for quite some time now, and now I was getting curious as to the new trend of mobile application development.

In my earlier post I talked about how I went in search of the best tools for mobile development.

I finally found my way to JQuery Mobile (JQM). And after all the talk and buzz around the tech space about developing mobile sites with JQuery mobile, I discovered that it isn’t as dreadful and uphill as people make you think.

The first thing you need to know is that JQuery mobile or JQM as it is often referred to as, is only just JQuery with an added css file for mobile rendering and a juery mobile javascript file.

So all you need to set up a mobile friendly page is add these 3 files to your header.

jquery.mobile-1.1.0.min.css,

jquery-1.7.1.min.js,

jquery.mobile-1.1.0.min.js

You will have to forget about XHTML validation in this case. Below is the typical structure of the head of a mobile page. You don’t have to start by creating a theme in themeroller as the default JQM theme is just good enough for you to start practicing with right away.

<!DOCTYPE html>

<html>

<head>

<meta name=”viewport” content=”width=device-width, initial-scale=1″ />

<link rel=”stylesheet” href=”css/jquery.mobile-1.1.0.min.css” />

<script type=”text/javascript” src=”js/jquery-1.7.1.min.js”></script>

<script type=”text/javascript” src=”js/jquery.mobile-1.1.0.min.js”></script>

</head>

<body>


Once you have these files in your header you are ready to start using JQM to perform all the mobile magic wonders that you see the so-called “mobile-experts” performing.

You can create lists that look like a phone’s native application navigation list and those fancy rounded buttons that slide into different pages when you click them, all simply using very basic html tag properties called the data-role.

For a detailed guide on the different features and properties in JQM, you may visit the JQuery mobile introduction page here.

After you are done with learning the HTML tag structures and properties in JQM, you can then add PHP into the mix to generate valid JQM tags that will render perfectly in mobile browsers.

The built-in Ajax functionality in JQM means you don’t have to worry about how to communicate with your scripts on the server, just return the results in a suitable format.

Finally, if you need to convert your mobile site into a native phone application, there are several tools that will take your pages and compile them into any platform of your choice.

A good example is PhoneGap.

&lt;

What are the Best Tools For Mobile Application Development?

I recently had a strong hunch about mobile based development seeing I live in a country where almost 100 million people haver access to mobile phones.

Looking at the available platforms with the only motive being to develop for the platform that has the most delightful qualities.

I was looking for the following:

1. A very popular mobile phone platform. By platform I mean the Operating system and mobile devices together.

2. A mobile platform that has very good penetration in Africa, and Nigeria, or one that is gaining user adoption fast.

3. A platform that supports economy class mobile devices, and not just the high end devices like the iPads, etc.

4. A platform that supports HTML 5 and has existing tools for seamless mobile application development and testing. The testing part being very, and I mean VERY important.

5. A platform

So I decided to hold off this post for a while up until I found a solution to this heinous situation. I tested some of these tools to see how well they did on my list of qualities above.

If you guessed my result would be awesome and very encouraging, then I can only say you are a very optimistic individual and may your wishes come true. But that assumption was not to be.

Looking through Blackberry (RIM), Android, and IOS (Apple), these seem to be the most active platforms outside of the world of feature phones that have literally flooded the emerging markets of the developing world.

It would be best to develop for at least one of these platforms.

So after some considerations, I settled with the blackberry option. My first experience was a hard stumbling block as the first tool I downloaded and tried (Ripple) was a total mess. Maybe my timing was wrong, but I happened to get a version of Ripple that just didn’t work.

Looking though forums and blog posts, I could only find out that many people had the same problem and could not find a solution.

Finally I settled for the Chrome browser plug-in which seemed to work fine. I wonder why I didn’t consider that option first.