Borrowing System
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 84 of 91.
Challenge
EasyLet's bring our Library Management System to life by creating the Library class that orchestrates all borrowing operations. This central coordinator will manage the book collection and enforce the rules that keep our library running smoothly.
You'll organize your code across four files:
Book.php— YourBookclass from the previous lesson 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. Create aLibraryclass that manages the book collection. Your library should have:- A private
$booksarray to store books indexed by ISBN addBook(Book $book): void— adds a book to the collectionfindBook(string $isbn): ?Book— returns the book or null if not foundborrowBook(User $user, string $isbn): string— validates and processes borrowing, returning appropriate messagesreturnBook(User $user, string $isbn): string— processes returns and updates both book and user state
The
borrowBookmethod should check three conditions in order and return these exact messages:"Book not found"— if the book doesn't exist"Book is not available"— if already borrowed"Borrowing limit reached"— if user has 3 books"Successfully borrowed: [title]"— on success
The
returnBookmethod should return"Book not found"if the book doesn't exist, or"Successfully returned: [title]"on success.- A private
main.php— Include the Library file. You'll receive two inputs: an ISBN and a book title.Create a
Library, aUserwith ID1and name"Alice", and aBookwith the provided ISBN, title, and author"Unknown". Add the book to the library, then perform these operations and print each result on a new line:- Borrow the book
- Try to borrow the same book again
- Return the book
- Borrow the book once more
This challenge demonstrates how the Library class centralizes business logic — it validates conditions, coordinates state changes across Book and User objects, and returns meaningful feedback for each operation.
Try it yourself
<?php
require_once 'Library.php';
// Read input
$isbn = trim(fgets(STDIN));
$title = trim(fgets(STDIN));
// TODO: Create a Library instance
// TODO: Create a User with ID 1 and name "Alice"
// TODO: Create a Book with the provided ISBN, title, and author "Unknown"
// TODO: Add the book to the library
// TODO: Perform these operations and print each result on a new line:
// 1. Borrow the book
// 2. Try to borrow the same book again
// 3. Return the book
// 4. Borrow the book once more
?>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