0
0
PHPprogramming~30 mins

Repository pattern in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Repository Pattern in PHP
📖 Scenario: You are building a simple PHP application to manage a list of books. To keep your code clean and organized, you want to use the Repository pattern. This pattern helps separate the data storage logic from the rest of your application.
🎯 Goal: Create a basic Repository pattern implementation in PHP to store and retrieve books. You will create a data array, a repository class, and use it to get all books.
📋 What You'll Learn
Create an array of books with exact titles and authors
Create a BookRepository class with a method to get all books
Use the repository to retrieve and print the list of books
💡 Why This Matters
🌍 Real World
The Repository pattern helps keep your PHP code organized by separating data access from business logic. This makes your code easier to maintain and test.
💼 Career
Many PHP frameworks and professional projects use the Repository pattern to manage data. Knowing this pattern is useful for backend development jobs.
Progress0 / 4 steps
1
Create the books data array
Create a PHP array called $books with these exact entries: ['title' => '1984', 'author' => 'George Orwell'], ['title' => 'To Kill a Mockingbird', 'author' => 'Harper Lee'], and ['title' => 'The Great Gatsby', 'author' => 'F. Scott Fitzgerald'].
PHP
Need a hint?

Use a PHP array with three associative arrays inside, each with keys title and author.

2
Create the BookRepository class
Create a PHP class called BookRepository with a private property $books to hold the books array. Add a constructor that accepts a parameter $books and assigns it to the property $this->books.
PHP
Need a hint?

Define a class with a private property and a constructor that sets this property from the parameter.

3
Add a method to get all books
Inside the BookRepository class, add a public method called getAll() that returns the $books property.
PHP
Need a hint?

Write a public method that returns the private books property.

4
Use the repository and print all books
Create an instance of BookRepository called $repository using the $books array. Then, use $repository->getAll() to get all books and print each book's title and author in the format: Title: [title], Author: [author] on separate lines.
PHP
Need a hint?

Create the repository object and loop through the books returned by getAll(). Use echo to print each book's details.