Using PHP more efficiently???

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
w1n78
Forum Newbie
Posts: 12
Joined: Mon Mar 08, 2010 10:55 pm

Using PHP more efficiently???

Post by w1n78 »

I am currently writing code from scratch every time. What I'm looking for is a faster and more efficient way of writing PHP code, something I can reuse. I know I can write my own classes but classes isn't one of my strong points. I'm still struggling on understand it, besides plenty of people have created and shared classes - but can't seem to find one that does all that I need. So what do I need?

A way to query the database. Every time I do a SELECT statement, I have to do 3 things every time.
- check if the SQL ran okay and display if an error has occurred
- check if records exists and display them
- if records don't exists, display message

Every time I do an INSERT statement, the following has to occur.
- check to make sure no duplicates are made

Every time I do an UPDATE statement, the following has to occur.
- check to make sure no duplicates are made

Every time I do a DELETE statement, the following has to occur.
- do not allow a record to be deleted if it will create orphan records on other tables

I have the database covered using foreign key constraints and other things.

I'm looking for a simpler way to paginate recordsets.

An easier way to handle authorization and authentication. I've created some functions to handle this and it seems to work out okay but I'm always looking for improvements or more efficient ways.

An easier way to implement layouts.

What I've tried...
- Dreamweaver: At first, it's a good solution but projects become more complicated so I end up having to write code by hand. Plus, DW code is ugly, long and inefficient.

- PEAR DB/MDB2: I tried to use this but documentation is little so I end up getting stuck.

- Include files: Very helpful for my layout problems but doesn't address the amount of repetitive code that handles database queries.

- Ruby on Rails: I started to use Rails and love it... until I get to the authentication/authorization part. The community can't seem to agree on what the best method/solution is. Another downside is the learning curve. I have to spend time learning things but once I get used to it, a lot of things can be automated. Also uses MVC which I'm still a noob with.

Things I'm about to try...
- PHP Adodb: This looks like a good database abstraction layer. Only thing I'm concerned about is it seems there hasn't been much activity in terms of making improvements and fixes.

- Smarty template: It looks good as well but will probably have to continue doing include files for different areas of the page layout. Should speed up development though - at least it looks like it will.

- CakePHP: Since I started to read about Rails, I'm starting to understand more about MVC architecture. But is this way too much for what I'm looking for?

So there you have it. My dilemma. I wasn't sure where I should post this since it seems to fit in more than one forum category. Hope this is the right place. I welcome any suggestions. Thanks for you time.
Griven
Forum Contributor
Posts: 165
Joined: Sat May 09, 2009 8:23 pm

Re: Using PHP more efficiently???

Post by Griven »

A PHP framework is definitely the way to go here. CakePHP or CodeIgniter are the ones I recommend you look at in this case. Cake is essentially Rails for PHP, but it is also larger and more complex than CodeIgniter. It really depends on whichever you prefer, and which meets your needs.

In addition, you're really going to have to close the gap in your knowledge of classes. I know where you're at right now, as I was in pretty much your exact same position just several months ago. "Which CMS is good for me?", "How do I use classes?", "How do I cut down on repetetive code", etc, etc.

As you've already seen, shared classes typically get you most of the way there, but are usually lacking the finer points that are unique to your own situation. It's at these times that one of PHP's greatest strengths, it's openness, really comes in handy. You can just look at the classes's source code and tweak it however you see fit (easier said than done, I know--it is possible, however).
w1n78
Forum Newbie
Posts: 12
Joined: Mon Mar 08, 2010 10:55 pm

Re: Using PHP more efficiently???

Post by w1n78 »

thanks Griven. reading some articles about CakePHP, it just seemed more than what i need for my needs. but it looks like it is a good solution since projects differ in size. i also read a few articles about CakePHP vs CodeIgniter and i prefer going with CakePHP. i will try CakePHP and see how far i can get with it.

i really want to learn more about classes but can't seem to find an article that i can understand. i get the general idea of what classes are but when it comes to syntax, that's where i have a rough time. can you share some links to resources that can help me out in that area?
Griven wrote:A PHP framework is definitely the way to go here. CakePHP or CodeIgniter are the ones I recommend you look at in this case. Cake is essentially Rails for PHP, but it is also larger and more complex than CodeIgniter. It really depends on whichever you prefer, and which meets your needs.

In addition, you're really going to have to close the gap in your knowledge of classes. I know where you're at right now, as I was in pretty much your exact same position just several months ago. "Which CMS is good for me?", "How do I use classes?", "How do I cut down on repetetive code", etc, etc.

As you've already seen, shared classes typically get you most of the way there, but are usually lacking the finer points that are unique to your own situation. It's at these times that one of PHP's greatest strengths, it's openness, really comes in handy. You can just look at the classes's source code and tweak it however you see fit (easier said than done, I know--it is possible, however).
Griven
Forum Contributor
Posts: 165
Joined: Sat May 09, 2009 8:23 pm

Re: Using PHP more efficiently???

Post by Griven »

Honestly, I never could find a resource about classes that I liked. I pieced it together myself from what I could find. So I'll do my best to write something here that should help you out.

Classes, much like functions, are used to cut down on repetitive coding. The difference here is that classes contain functions. These functions will act as methods once you create an instance of your class inside your program. This instance that you create is called an object--hence the term "object-oriented".

Let's say that we have a class called "Database". Inside that class is one function called "Select". Below is the code for such a class.

The class

databaseclass.php

Code: Select all

<?php
class Database {
 
    //This is a class constructor.  The code inside a constructor is run each and every time an instance of a class is created.  In this particular case, we want our class to connect to the database every time we create an instance of it.  
  function __construct(){
    mysql_connect('localhost','root','password');
    mysql_select_db('myDatabase');
  }
 
  function select(queryString){
    $result = mysql_query(queryString);
 
      //In large applications, error handling can become very redundant without the use of classes.  Using a custom class to query your database and handle any errors is handy, and can really cut down on the amount of code you have to type.  Each time the "select()" method is run in this class (more on how to run it later), error handling will occur.
 
    if (!$result) {
      echo 'Couldn't find your data';
      exit();
    } else {
      return $result;
    }
  }
 
}
?>
 
Most classes would have more than one function. However, as this is just an example, one function will be enough.

At this point, you may be wondering, Why not just use functions?. The simple answer to this question is "organization". Classes help you group together bits of functionality. They also allow you to share those bits of functionality amongst the various functions inside your class (which is beyond the scope of this short tutorial).

Putting it to use

Now that we have a class created, it's time to use it. In order to do that, we have to create an instance of it within our code.

index.php

Code: Select all

<?php
  //Include the database class page--note that this does NOT create an instance of the class
include('databaseclass.php');
 
  //Now let's create an instance of the class.  This is called an OBJECT
$db = new Database;
  //At this point, all the functions inside the Database class are available as methods to the $db object.
 
$result = $db->select("SELECT * FROM myTable");
  //Notice the arrow syntax here.  That is how we call a method.  Each method name must correspond to a function inside of the class.  This particular bit of code will either return the resultset from the database and store it in the $result variable, or it will echo an error and terminate the program, as a result of our built-in error handling.  See how that cuts down on repetitive code?
?>
Where to go from here

Hopefully what I've written here is clear and understandable. If it is, then you've got the basics of classes down, and you can probably move onto learning about things such as method scope and class inheritance. I would explain it here, but I don't want to push this tutorial beyond the basics.

If you have any further questions, please feel free to send me a PM, or an IM. I'll be more than happy to answer any questions that you may have.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Using PHP more efficiently???

Post by Weirdan »

Griven wrote: At this point, you may be wondering, Why not just use functions?. The simple answer to this question is "organization". Classes help you group together bits of functionality. They also allow you to share those bits of functionality amongst the various functions inside your class (which is beyond the scope of this short tutorial).
Another benefit of an object is that it groups together related data and functions (incapsulation) . Consider the silly example of displaying html select:

Code: Select all

 
class Select {
   protected $_options = array();
   protected $_tagOptions = array();
   public function __construct($tagOptions) {
       $this->setTagOptions($tagOptions);
   }
   public function setTagOptions($tagOptions) {
       $this->_tagOptions = $tagOptions;
   }
   public function add($option, $key = null) {
       if (is_null($key)) {
          $this->_options[] = $option;
       } else {
          $this->_options[$key] = $option;
       }
   }
   private function _renderTagOptions() {
       $ret = '';
       foreach ($this->_tagOptions as $k => $v) {
         $ret .= htmlspecialchars($k) . '="' . htmlspecialchars($v) . '"';
       }
       return $ret;
   }
   public function __toString() {
       $ret = '<select ' . $this->_renderTagOptions() . '>';
       foreach ($this->_options as $k => $v) {
           $ret .= '<option value="' . htmlspecialchars($k) . '">' . htmlspecialchars($v) . '</option>';
       }
       $ret .= '</select>';
       return $ret;
   }
}
$select = new Select(array('name' => 'mySelect', 'id' => 'mySelect'));
$db->query('select name, value from site_options')->toSelect($select); // assuming query() would return an object for a result set which would call add() method on the $select for every line of the result set
echo $select;
 
Here we grouped together relevant data ($tagOptions and $options) and methods to work on that (add() and __toString()). Also we used private helper method (_renderTagOptions) to demonstrate that classes might be used to limit access to some methods.
Post Reply