Search Functionality
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 85 of 91.
Challenge
EasyLet's enhance our Library Management System by adding search functionality. Users need to find books easily, whether they're looking for a specific title, browsing by author, or checking what's currently available to borrow.
You'll organize your code across four files:
Book.php— YourBookclass with readonly properties (isbn,title,author), a private$isAvailableproperty starting astrue, and methods:isAvailable(),markAsBorrowed(), andmarkAsReturned().User.php— Include the Book file. YourUserclass with readonly properties (id,name), a private$borrowedBooksarray, aMAX_BOOKSconstant of3, and methods:getBorrowedBooks(),canBorrow(),addBook(Book $book), andremoveBook(string $isbn).Library.php— Include the User file. Expand yourLibraryclass with the existing functionality plus three new search methods:searchByTitle(string $keyword): array— returns all books where the title contains the keyword (case-insensitive)searchByAuthor(string $author): array— returns all books where the author name contains the search term (case-insensitive)getAvailableBooks(): array— returns only books that are currently available for borrowing
Use
array_filterwith arrow functions andstriposfor case-insensitive matching. Remember thatstriposreturnsfalsewhen no match is found, so check for!== false.main.php— Include the Library file. You'll receive two inputs: a search keyword and an author name.Create a
Libraryand add these four books:- ISBN:
"978-0", Title:"PHP Basics", Author:"John Smith" - ISBN:
"978-1", Title:"Advanced PHP", Author:"Jane Doe" - ISBN:
"978-2", Title:"Python Guide", Author:"John Smith" - ISBN:
"978-3", Title:"Web Development", Author:"Alice Brown"
Borrow the book with ISBN
"978-1"using aUserwith ID1and name"TestUser".Then perform these searches and print the results:
- Search by title using the first input, print each matching book's title on a new line
- Search by author using the second input, print the count of matching books
- Get available books and print the count
Output format:
Title matches: [title1] [title2] ... Author matches: [count] Available: [count]- ISBN:
This challenge demonstrates how array_filter combined with stripos creates powerful, user-friendly search functionality. The case-insensitive matching means users don't need to worry about exact capitalization when searching.
Try it yourself
<?php
require_once 'Library.php';
// Read inputs
$searchKeyword = trim(fgets(STDIN));
$authorName = trim(fgets(STDIN));
// TODO: Create a Library instance
// TODO: Add the four books to the library:
// ISBN: "978-0", Title: "PHP Basics", Author: "John Smith"
// ISBN: "978-1", Title: "Advanced PHP", Author: "Jane Doe"
// ISBN: "978-2", Title: "Python Guide", Author: "John Smith"
// ISBN: "978-3", Title: "Web Development", Author: "Alice Brown"
// TODO: Create a User with ID 1 and name "TestUser", register them
// TODO: Borrow the book with ISBN "978-1"
// TODO: Search by title using $searchKeyword and print results
echo "Title matches:\n";
// Print each matching book's title on a new line
// TODO: Search by author using $authorName and print the count
echo "Author matches: " . /* count here */ "\n";
// TODO: Get available books and print the count
echo "Available: " . /* count here */ "\n";
?>All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern