Building Classes
In this post we build a class to process recipes in a recipe app. We will explore how to initialise a class, define properties, create objects and call methods.
So what do we want our class to do?
- Fetch recipes
- Add recipes
- Update recipes
- Remove recipes
Let’s define our class
process_recipes.php class Process_recipes { //Define functions here public function fetch_recipes() { return true; } public function add_recipe($recipeData) { return true; } public function update_recipe($recipeData) { return true; } public function delete_recipe($recId) { return true; } }
What’s happening?
Here we are defining a Process_recipes class and we have defined four public methods, fetch, add, update and delete recipes. These are public methods because we need to access them from another part of the application.
Tip: When naming classes it’s a good idea to save the files using the same name as the class. This can help with auto-loading classes as well as code maintenance.
How do we call our class?
Now we have defined our class we need to make use of it.
index.html require 'process_recipes.php'; $recipe = new Process_recipes; $recipe->fetch_recipes();
What’s happening?
Here we are instantiating our recipes class. Notice the NEW keyword. This means create a NEW object based on the Process_recipes class. We then call the fetch_recipes method using the -> operator.
What have we explored in this post?
We have identified how to define a class and specify public methods. We then built a controlling script to call our class and invoked our first method fetch_recipes().