Book and User Classes
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 83 of 91.
Challenge
EasyLet's build the foundation of our Library Management System by creating the Book and User classes. These core domain objects will work together to manage library operations.
You'll organize your code across three files:
Book.php— Create aBookclass that tracks library books. Your book should have three readonly properties set via constructor promotion:isbn,title, andauthor. Include a private$isAvailableproperty that starts astrue. Add three methods:isAvailable(): bool— returns the availability statusmarkAsBorrowed(): void— sets availability to falsemarkAsReturned(): void— sets availability to true
User.php— Include the Book file and create aUserclass representing library members. Your user should have two readonly properties via constructor promotion:id(int) andname(string). Include a private array$borrowedBooks(initially empty) and a constantMAX_BOOKSset to3. Add these methods:getBorrowedBooks(): array— returns the borrowed books arraycanBorrow(): bool— returns true if the user has fewer than MAX_BOOKS borrowedaddBook(Book $book): void— adds a book to the borrowed arrayremoveBook(string $isbn): void— removes a book by ISBN usingarray_filter
main.php— Include the User file and bring your classes to life. You'll receive four inputs: a user ID, user name, book ISBN, and book title (author will be"Unknown").Create a
Userand aBookwith the provided values. Print whether the user can borrow initially, then have the user borrow the book (mark it as borrowed and add it to the user). Finally, print the book's availability and the count of borrowed books.Output format:
Can borrow: [yes/no] Book available: [yes/no] Books borrowed: [count]
Notice how encapsulation protects the internal state — a book's availability only changes through dedicated methods, and a user's borrowed books are managed through controlled access. This foundation will support the borrowing system we'll build next.
Try it yourself
<?php
require_once 'User.php';
// Read inputs
$userId = intval(trim(fgets(STDIN)));
$userName = trim(fgets(STDIN));
$bookIsbn = trim(fgets(STDIN));
$bookTitle = trim(fgets(STDIN));
$bookAuthor = "Unknown";
// TODO: Create a User object with the provided id and name
// TODO: Create a Book object with the provided isbn, title, and author
// TODO: Print whether the user can borrow initially
// Format: "Can borrow: yes" or "Can borrow: no"
// TODO: Have the user borrow the book:
// - Mark the book as borrowed
// - Add the book to the user's borrowed books
// TODO: Print the book's availability
// Format: "Book available: yes" or "Book available: no"
// TODO: Print the count of borrowed books
// Format: "Books borrowed: [count]"
?>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