New Feature: Playlist Center! Pick a topic and let our playlists guide the way—like a learning mixtape.

Start learning with our library of video tutorials taught by experts. Get started

Object-Oriented Programming with PHP
Illustration by

Creating a database class


From:

Object-Oriented Programming with PHP

with Jon Peck

Video: Creating a database class

Often it's optimal to only connect to the database once. I could connect and disconnect every time I needed to query the database, but that's hugely inefficient. I could use a global variable assigned to the connection, but that's fragile at best, as anything could manipulate it. It's better to control access, and restrict the number of connections. I am going to demonstrate how to create a simple, but still useful class that will only allow one connection to the database at one time. It'll provide access throughout the application, and minimize the possibility for corruption.
Expand all | Collapse all
  1. 4m 10s
    1. Welcome
      39s
    2. Exercise files
      2m 16s
    3. What you should know
      1m 15s
  2. 7m 47s
    1. What is an object?
      2m 6s
    2. What is a class?
      2m 7s
    3. Why should you use object-oriented programming?
      2m 14s
    4. The history of object-oriented PHP
      1m 20s
  3. 16m 40s
    1. Defining a class
      2m 58s
    2. Defining class properties
      3m 26s
    3. Creating a method and exploring object context with $this
      2m 50s
    4. Instantiating an object and accessing its contents
      3m 19s
    5. Specifying the visibility scope
      4m 7s
  4. 15m 51s
    1. What is a magic method, and do I need one?
      2m 23s
    2. Overloading property access
      6m 37s
    3. Customizing object construction
      4m 34s
    4. Standardizing object rendering as a string
      2m 17s
  5. 20m 54s
    1. Using the static keyword
      3m 36s
    2. Leveraging scope resolution operators
      1m 10s
    3. Setting constant values
      2m 47s
    4. Implementing static methods
      5m 43s
    5. Creating a database class
      7m 38s
  6. 26m 19s
    1. Extending your class
      6m 8s
    2. Abstracting classes
      5m 57s
    3. Sharing interfaces using polymorphism
      4m 39s
    4. Overriding methods, properties, and constants
      3m 25s
    5. Cloning and comparing objects
      2m 51s
    6. Referencing objects
      3m 19s
  7. 14m 52s
    1. Leveraging standard class objects
      2m 42s
    2. Retrieving objects from the database
      5m 41s
    3. Error handling with exceptions
      2m 6s
    4. Customizing PHP exceptions
      4m 23s
  8. 8m 2s
    1. Identifying the singleton pattern
      1m 42s
    2. Using the factory method pattern
      1m 51s
    3. Implementing a strategy pattern
      4m 29s
  9. 2m 57s
    1. Looking forward to namespaces
      47s
    2. Next steps
      1m 6s
    3. Goodbye
      1m 4s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
please wait ...
Object-Oriented Programming with PHP
1h 57m Intermediate Sep 26, 2012 Updated Apr 10, 2013

Viewers: in countries Watching now:

Whether you're enhancing or optimizing existing code or just starting from scratch, there's never a better time to start integrating object-oriented design techniques. This course shows how to integrate the principles of object-oriented programming into the build of a PHP-driven web page or application. After an overview of what objects and classes are and why they should be used, author Jon Peck dives into creating and instantiating objects, then defining the class relationships and interactions that will form the basis of your coding arsenal. The course also shows how to leverage PHP objects and implement design patterns, and looks at steps you can take to continue adding to your programming tool belt.

Topics include:
  • Historical overview of object-oriented PHP
  • Defining classes
  • Creating a method/object context with $this
  • Accessing classes without instantiation
  • Creating a database class
  • Extending and abstracting classes
  • Cloning and comparing objects
  • Error handling with exceptions
  • Implementing design patterns, such as the factory and strategy patterns
Subjects:
Developer Programming Languages
Software:
PHP
Author:
Jon Peck

Creating a database class

Often it's optimal to only connect to the database once. I could connect and disconnect every time I needed to query the database, but that's hugely inefficient. I could use a global variable assigned to the connection, but that's fragile at best, as anything could manipulate it. It's better to control access, and restrict the number of connections. I am going to demonstrate how to create a simple, but still useful class that will only allow one connection to the database at one time. It'll provide access throughout the application, and minimize the possibility for corruption.

To do that, I'm going to use the object- oriented database connection from the MySQLi improved extension (or MySQLi). Create a new file in your Exercise folder, and call it class_Database.inc. Start a new class definition for the database. And, add some documentation. Only one connection is allowed.

The first property to create will contain the connection. Make it private, as the class will be controlling access to it. Next, make a private static property called instance. Remember, static properties can be changed after being defined, and the value is stored at the class level. private static $_instance. Provide a public static method to allow any part of the program to access the database instance.

public static function getInstance. If the instance does not exist, create it using self, only as a function call. if not self instance, self ::$_instance = new self. Then, return the static instance. return self::$_instance. Add proper documentation, get an instance of the database, and return type database.

Now, define the constructor for the database object. public function __construct. Start the constructor with a new MySQLi connection. The arguments are in the following order: host, username, password, and database name. As your environment may be different from mine, take note of your connection details, and replace as necessary. Error handling, if mysqli_connect_ error, then trigger error (failed to connect to MySQL, followed by my mysqli_connect_ error(), and we'll set the level as E_USER_ERROR;.

I want to prevent the database connection from getting copied, so I'll use the magic method clone, which specifies how an object is duplicated. I'll get into object cloning a bit later on, but for now, I'll just define an empty clone magic method, which will do nothing, including no copying, which is exactly what I want. Empty clone magic method to prevent duplication, private function __clone, and two curly braces ({}).

Finally, define a public method for getting the MySQLi connection. Get the MySQLi connection. Public function getConnection. return $this->_connection. Save the file. Now that a database connection is available, let's go back to the Address class, and get rid of the placeholder postal code lookup. Navigate to _postal_code_ guess, and replace the contents.

First, get an instance of the database. Next, get the connection. Write the SQL query. You'll want to get the postal code from the location table on the database, which is provided in the Exercise Files. SELECT postal_code from location.

Escape the variables, as the biggest danger to your application is user input. city_name is mysqli->real_escape_string ($ this->city_name); WHERE city_name = $city_name. We'll do the same for the subdivision name. $this->subdivision_name; AND subdivision_name = execute the query that you have created. $result = mysqli->query($sql_query).

If there was a match, we turn the postal code if ($row = $result->fetch_associative array, return $row 'postal code'. Save the Address class, then return to the demo file. As we've created a new database class, required at the top. require 'class.Database.inc. This file has gotten a bit long with all the testing, so let's simplify a bit.

Remove the empty address. Next, unset the postal code in the first address to test the new lookup. Then, replace the var export, and display after setting the address properties with an echo address, using the two-string magic method. Remove the Testing magic __get and __set. In the second address, remove the postal code, then replace the explicit call to display with echo $address_2. We don't need to debug the address types anymore, so they can be safely removed.

Save the demo, then return to the browser, and refresh. I can see that the postal codes are still being displayed, but now they're coming from the database. In this chapter, we accessed classes without instantiation. First, I discussed how to use the static keyword. I used the scope resolution operator to access static properties and methods. I demonstrated how to set constant values in the class, which never change, then implemented a static method to validate address type IDs. Finally, I created the database class to only allow one connection at a time.

With this foundation and ability to control access to resources, you have the beginnings of a stable and robust system, logically-structured and named. In the next chapter, I'll add further structure and hierarchy using class relationships.

Find answers to the most frequently asked questions about Object-Oriented Programming with PHP.


Expand all | Collapse all
please wait ...
Q: I'm not seeing warnings or errors in my environment like the video; why not?
A: Your PHP configuration is probably configured not to show them to you. This is often true on commercial web hosts and is often the default. Fortunately, there are multiple ways of resolving this.

The easiest way would be to explicitly enable error reporting at the top of the PHP script you wish to debug.

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);

Alternatively, if you have access to your php.ini file and you want to always have error reporting on, change error_reporting = to a development friendly value of

error_reporting = E_ALL | E_STRICT

then change display_errors = to

display_errors = On

Finally, if access to the php.ini file is not available, you can add the following directives to your .htaccess or VirtualHost configuration for Apache:

php_value error_reporting 32767
php_value display_errors 1

If you would like a development optimized development environment like the one utilized in this course, see Up and Running with Linux for PHP Developers, here in the lynda.com online training library.

Q: This course was updated on 4/10/2013. What changed?

A: The author rerecorded some of the tutorials to add more background information and better graphics.

 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now Upgrade now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Object-Oriented Programming with PHP.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Notes cannot be added for locked videos.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.