Category » PHP


I've been developing a site using Wildflower CMS developed using CakePHP and ran into an infuriating problem. After working on it for several weeks without issue I started receiving javascript errors that caused everything to come to a grinding halt. The errors were all reported using Firebug and the javascript debugger. The culprit:

Unterminated String Literal

After that in the Firebug console was:

$ is not defined

I knew there was a strong possibility that the first error was somehow causing the second and that top-down debugging was the way to go. After inspecting the javascript code I discovered that there was a variable assignment going on that spanned several lines. This might be legal in PHP but not javascript.

Zend Certified EngineerI passed the Zend PHP5 Certification Exam last week and thought I would share my experience with it.

Zend Yellow Pages

I decided that I wanted to take the test about 2 1/2 months ago. The first thing I did was visit the site and learn more about the exam itself. I discovered it covers almost every facet of the language and its use. Here is a breakdown of the major sections:

  • PHP Basics
  • Functions
  • Arrays
  • Object Oriented Programming
  • Security
  • XML & Web Services
  • Strings & Patterns
  • Databases & SQL
  • Web Features
  • Streams & Network Programming
  • PHP 4/5 Differences
  • Design & Theory

You can get a more details topic list for each section on the PHP5 Certification Landing Page.

For the first month I spent time reading e-books and other free material on the subjects mentioned above that I felt weak in. I was not very devoted during the first month and only spent a couple hours (3-5) each week.

At the beginning of the second month, I purchased two books recommended by a lot of others who passed the exam.

Zend PHP Certification Study Guide - Zend Technologies

Zend PHP Certification Study GuideThe first book is published by Zend and is 'the official study guide to prepare for the Zend PHP Certification exam'. I liked this book because it was very focused and clear about the topics it was covering. It also has a couple of practice questions at the end of each chapter to prepare you for the real thing.

There is also a glossary of terms that help you become familiar with some of the terminology used. Not sure what a HEREDOC or MTA is? Look it up quickly with this book.

This book does have a few technical errors in some examples that you do need to watch out for.

 

Zend PHP Certification Study Guide 2nd Edition - Davey Safik and Ben Ramsey

Zend PHP 5 Certification Study GuideI actually started reading this book first. This book contains more information about each topic but seems less focused. What I mean is that the major topics are covered and explained fairly well but it doesn't go as in-depth when it comes to sub-topics. I frequently caught myself going to this book when I needed more general information about something but tended to stay with the aforementioned book because it helped me stay focused.

This book does not contain any practice questions or glossary, which is a bummer.

 

 

Zend PHP 5 Certification Online Practice Testing

My last resource was the online practice tests made available Zend. They are in the same format as the real test: 70 questions with a 90 minute timer. The layout of the actual test is a little different than these practice tests but nothing significant. The advantage to these practice tests is that you can go on past the 90 minutes and it will give you two scores. One when the time expired and the other is based on the final submission.

It's important to note that the practice tests do not tell you how you did on each question. Rather it breaks the test down into each major section and gives you one of three scores - fail, pass, or passed with flying colors. I found this to be very annoying but understood the intended benefit.

I took a total of 5 exams out of the 10 that I purchased. After the 5th exam a significant number of questions were repeats which really took away from the 'fear' and 'anxiety' factor of the test. I heavily recommend you take the test until you pass with flying colors in each major section to be ready for the real thing.

 

Overview

It's been mentioned before and I agree that none of these resources alone are enough to make you feel confident going into the test. Rather, a combination of each resource should be taken advantage of to feel fully prepared. I took every practice question in Zend's book twice and read the entire book two or three times total. I spent a good deal of time in PHP Architect's book but probably only read it front-to-back once.

I consider the practice test to be the most beneficial. I took one test almost immediately after I purchased them to have a baseline benchmark. With a general idea of where I stood in each section I was able to concentrate my studying in those sections. After I was satisfied that I had improved I retook the test and repeated the process until I passed every section with flying colors.

Even with this I still considered the real test to be difficult. The practice test claims to be generally harder than the exam - In my opinion, this is not true.

The style of questions was very test-like. They were very obscure blocks of code that obviously had no real-world use but still covered several very important concepts. There are four types of questions:

  • Single choice questions - Multiple choice, choose one
  • Multiple choice questions - Multiple choice, choose several
  • Fill in the blank questions - Several blanks in a sentence, choose from multiple possible answers
  • Open questions - fill in the blank (text input)

 

Test Day!

The test was observed by a proctor at a Pearson Vue testing center of my choice. They took all my belongings and stored them in a secure area (unlocked closet), sat me down in front of a computer, and gave me a laminated sheet of legal-length paper with a dry-erase marker (no eraser, although I'm sure I could have asked for one). The proctor starts the exam and after a few screens explaining the rules, agreeing to a NDA, andmaking sure I was ready, the test began.

I can't really talk much about the test or specific questions that were asked but I can say that they were from every topic. A good variety of mixed-up questions. I don't believe it was the type of test where the questions adjusted themselves based on whether or not you answered correctly or not. It is important to note that there are trick questions.

I found these questions in the book, practice exam, and the exam itself. There would be large blocks of code that would never get executed because of some small detail. I don't believe they are intended to be tricky just for the sake of amusing the test-authors, rather to see if you really pay attention to details in the code. I think we can all agree that attention to detail is of utmost importance in this profession.

Once you have completed all 70 questions you are presented with a chance to go back to any particular question and re-evaluate your answer. Once you're satisfied with your performance you submit the test for grading. After a couple seconds (seemed like days) of plugging and chugging you get a screen with either Pass or Fail. The proctor hands you a printed certificate with your candidate number, grade, and sends you on your way.

 

Tough Subjects

These were the toughest subjects for me because I do not use them very often:

  • Bitwise operators.
  • Data Types
  • XML & Web Services.
  • Type Hinting
  • Database topics - PDO, mysqli, transactions, and other database technologies.
  • A lot of functions. I had to memorize a lot of functions that I forgot about or used often yet never seemed to remember the parameter order or particular definition. I've become conditioned to pull up the PHP manual and look something up in my sleep. The function you need to know pulled from every corner of PHP. Strings, arrays, files, and network streams just to name a few.
  • Nuances of PHP's variable juggling.
  • And more!

 

Conclusion

I spent a lot of time studying at my leisure but really buckled down the last two weeks leading up to the exam. As I said before, none of the resources I found are enough to make you feelconfident going into the test. Rather, all of them together do a nice job preparing you. There are a lot of questions on subjects that you probably have never used in the past and may never use in the future. I recommend spending some extra time as you may have to memorize several key functions and their parameters for the exam.

I'm glad I spent the time and effort to earn the certification. I know that there are those out there who question its usefulness but I found it extremely helpful. Not only do I find myself more confident in my abilities to use the language properly, but I get to use the Zend logo on my site :)

 

I just ran into an interesting question while studying for the Zend certification, and I thought I would share because I was very confused.

What is the output of the following:

<?php
$a 
010;
$b 0xA;
$c 2;

print 
$a $b $c;
?>

Over the next couple weeks I'm going to be writing a series on programming design patterns and their applications. I plan to cover the popular patterns as well as the lesser-known, yet still insanely useful, ones too. This first article will go over the background and basics of a design pattern - What they are, why you should care, and how to implement one into your application. 

Often one of the first patterns that young developers encounter, the singleton solves a very sloppy, dangerous, and nightmarish practice known as global variables. There are components in nearly every application that need to be accessed everywhere. Configuration variables are a perfect example of this. The younger developers might be tempted to declare a debug variable as global, and just access it where he/she pleases. You will learn later on in the project that this makes maintaining the application very frustrating.

We have all gone back and looked at code we wrote in the past and thought "Wow, this is ugly.", or "wtf was I thinking?", or even "I wrote this yesterday, and I have no idea what it does." Refactoring is the process of going back over already-working code and cleaning it up for the sole purpose of understandability, maintainability, and preserving your self-worth if anyone else were to take a peak. No one likes to be humiliated by their own code.

CakePHPI have fallen in love with CakePHP's integration of the SimpleTest libraries. With the type of work that I normally do, unit-testing is hard to utilize successfully. That is to say, most of the applications I work on have very straight-forward components and not a lot of complex functions/methods. I would only be testing whether or not they worked at all, rather than if they worked in a wide-array of situations.

For example, unit-testing a simple news list and detail page is probably overkill. Sure, you can test your classes by simple instantiating them but that only goes so far. My new method involves using SimpleTest's Scriptable Browser to actually crawl webpages and ensure that the proper data is being displayed. That way, I can catch all my php errors, including notices and warnings, insure that the proper headers are being sent, and assert that certain text is appearing on the page. Unit-testing will rarely catch a poorly coded method that throws a PHP notice whereas the Scriptable Browser will.SimpleTest

 

Automagically generated date/time input fields normally default to the current date and time. For a couple of reasons, I had to change this to another default value. For example's sake, let's say I needed a time field to always select 1:30 pm in an add action.

Run of the mill example:

<?php
    
echo $form->input('start_dt');
?>

This will output 3 select boxes; one for hours, minutes, and the merdian (am/pm) with the current time pre-selected. So if it was 3:04 pm, that would be selected.

So lets change this so that 1:30 pm is always pre-selected:

<?php
    
echo $form->input('start_dt', array('selected' => array('hour' => '1',
                                                           
'minute' => '30',
                                                           
'meridian' => 'pm')
                                 )
                );
?>

That's all there is to it! Cake's automagic owns. Hope this helps someone else :)

CakePHPI've been doing a lot of work with CakePHP lately and it has been amazingly satisfying developing in a framework that encourages great coding practices. More on CakePHP, specifically, later. Right now, I'd like to present some things I've learned about the architecture that CakePHP is built on. I'm talking about the Model-View-Controller (MVC) architecture of course.

I'm hoping most of you reading know already know a thing or two about MVC but if you don't, here is a quick overview from wikipedia.

Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements.

KeyboardPHP's greatest strength is also its greatest weakness. Flexibility. There are an infinite number of ways to perform the same task which PHP will happily do without so much as a peep as to how poor the code really is. Sadly, most developers endure a trial by fire where they only learn from their mistakes after it's too late.

I suggest a more retro-active apprach. Studying, surrounding, and forcing yourself to abide by best-practice coding standards will yield surprising results in your applications despite the fact that it may seem like more work than it's worth.

I've come up with a list of things that I feel are most important to me when it comes to coding. So, without further adieu:

Site spam sucks, no doubt about it. I was getting tired of fighting it manually in hand-to-hand combat and decided to get some help. I'd heard about different techniques for thwarting comment, and other types of form, spam but none of them seemed to make a big enough dent in the problem for my liking. That is, until I tried Bad Behavior.

xdebugI finally got around to installing xdebug on my development environment and have decided it is the best thing since sliced bread.Installation was a breeze and the information it provides when something has gone wrong is incredibly helpful during debugging. What I didn't know, and hope to help others by documenting it here, was the amount of configuration options Xdebug has. The base install has some irritating limitations that are easily addressed with a few simple lines in the php.ini file.

PHP makes file system manipulation easy with its variety of built-in functions. One thing I always knew, but never got the chance to try, is that many of those same functions worked over FTP instead of the local file system. I finally got my excuse to give it the ole' college try and I found a few things that may help others with the same task.

PHPEvery good programmer should constantly be looking for ways to improve the look and readability of their code. One of my favorite ways to reduce vertical length while maintaining readability is to use the lesser-known ternary comparison operator.

The Ternary Operator is unique when it comes to PHP's available comparison options. Not in the sense that it does something that the other operators don't, but that the functionality it offers is not seen anywhere else.

<?php
  $myvar 
= ($x == $y) ? TRUE FALSE;
?>

PHPNoticing your pages are loading slowly or just don't like using extra cpu cycles when you don't have to? PHP makes caching very easy with their variety of Output Control Functions. In this article I'll go over complete page caching which is the easiest to implement and understand.

MySQLRelational Database Design is one of the most powerful ways to ensure data integrity and a great way to kick-off any project. Very often the first thing developers do when starting a new project, or stub-project, is to design the database. This way the structure of the application is already in place and we just have to fill in the pieces with some server-side code. I've found when adding relational constraints to your database design you add in a very powerful error reporting tool that will let you know during the development process that you have allowed something to happen that shouldn't have. In this article, I go through, step by step, showing how to set up a simple relational database and discuss the benefits that are enjoyed.

Blake over at PHP vs .NET has written up a very nice article to prepare those who are interviewing for a php job soon. He basically gives a bunch of php snippets and asks where the bugs are. The article somewhat morphs into a mish-mash of good-practice/bad-practice comparison and explains why one way is better than the other.

From the article:

Find the errors in the following code:

<?php
function 
baz($y $z) {
    
$x = new Array();
    
$x[sales]  = 60;
    
$x[profit] = 20:

    foreach(
$x as $key $value) {
        echo 
$key+" \"+$value+\"<BR>\";
    }

?>

A lot of the gripes about PHP as a language come down to the fact that there are a million ways to accomplish the same task, but only a couple are truely 'correct' - as in significantly better for one reason or another. Out of all those reasons script efficiency and speed are the driving force behind all experienced programmers.  That being said it's hard to know what the right way to do things are. Sure there are 100 ways to do something but all but 2 or 3 of those take an obscene amount of time. Normally, during development, you won't notice long load times because it's not getting hammered by thousands of users requesting the same page.

Chris Vincent has set up The PHP Benchmark to help visually show how some methods are more effecient than others.

PHPBench.com was constructed as a way to open people's eyes to the fact that not every PHP code snippet will run at the same speed.

A few highlights:

<?php
foreach($aHash as $val);
// VS
while(list(,$val) = each($aHash));
?>

  • foreach($array as $value) is the fastest way to loop through an array.
  • foreach($array as $key => $value) is slightly slower by about 10-15% so use it only when necassary.
  • Using while() and for() loops dramatically increases the server load especially when used in conjuction with list() and each().

Creating a way to show how many users are currently visiting your website has become a fad amongst webmasters. It's a cool way to show off your skills has a coder and to show your visitors how many other people are looking at the same thing they are. You don't want to miss the bandwagon again do you? This script is also an excuse to brush up on some mildly advanced MySQL queries.

The most useful and almost necessary feature of any interactive website is a registration form. A way to give users access to features while keeping out the riff-raff. While a registration script can be the perfect time for an amateur to grab the bull by the horns it can also leave lots of pitfalls for a more experienced programmer.

rssProviding RSS Feeds for your website is fast becoming a necessity in today's web2.0 world. The amount of surfers taking advantage of everything RSS Feeds has to offer has exploded in recent history, and it's easy to see why. The amount gained from offering a RSS Feed far outweigh the effort needed to create one.

After learning the basics of PHP's basic file system functions, the first thing you'll want to do is put it to use. One of the easiest and flashiest things you can create is a page counting script. I'll show you how to create a page hit script that is easy to create and even easier to implement.

Knowing the basics of cookies and sessions is essential to any successful PHP programmer. It is useful to store pieces information on the users computer for later use. Things like when they laste visited, language of choice, age, etc. Cookies and Sessions are the perfect solution to our needs.

  Browser needs Cookies Enabled? Can User Edit Information?

Information Lasts Between Browser Sessions?

(Leaving site and coming back) 

Information Location 
Cookies
 Yes  Yes, easily
 Yes  User's Browser
Sessions
 No
 No*  No  Server, except for session ID

The first thing I wanted to know after learning the basics of PHP was how to store my data on a more permanent basis. PHP is all well and good but without the ability to store data between browser sessions it has limited functionality. After learning how to store and retrieve data, your PHP scripts really come to life.