1. 44
    Refactoring functions into PHP classes
    3m 18s

Refactoring functions into PHP classes

Mark Shust
InstructorMark Shust
Share this video with your friends

Social Share Links

Send Tweet

Creating functions around your app is just fine, but when your app grows in complexity, you will want to create those functions as being part of PHP classes. This will help your app scale & expand with time.

Instructor: [0:00] We have this author class all set up, but we are still using this functions.php file and it's pretty sloppy. Let's convert this into its own class. Within the classes directory, let's go ahead and create a new file named post.php.

[0:20] Let's create a PHP tag and declare strict types, create our class named post, and next we will copy the contents from this functions.php file over to this new post class. First comes this require statement that we will place at the top above our class definition.

[0:43] Then we will grab both of these functions, getPost and getPostText, and paste them into our post class. Each of these functions really should have a scope defined.

[0:57] The default scope is public, but it's still a good idea to explicitly define these scopes as public to make it very apparent that this actually is what we want to do. Let's add public before each of these function definitions. Next, we also need to update the function names.

[1:19] We can remove any reference to post within the function name. Since post is already implied by the class name of post, naming these functions with posts within it is redundant. Let's rename getPosts to getAll, and going to getPostText, let's just rename this getText.

[1:43] This post class is a bit different from the author class, and we really don't need or want to instantiate this class. Because of this, we can also use the static keyword to define each of these as static functions. This means that we won't have to instantiate this class just to call one of its functions.

[2:02] We can just call the functions directly without instantiation. After public, let's add static to each of these function signatures. Now that we copied all of the functionality out of the functions.php file, we can go ahead and delete it.

[2:23] We will also need to update the index.php file since it still references functions.php. Rather than including this file, we will include a reference to classes/post.php. Then we can update the references for both the posts and post text variables. Since getPost doesn't exist, we can call the post class.

[2:50] Since we don't need to instantiate this class, we can just call the public static functions we defined with two colons, followed by the name of the class, which would be getAll. We can replace this second call with a call to post getText.

[3:09] If we refresh our page, we can see everything still functions exactly the same, so everything still works.