Menu
Coddy logo textTech

Recap - Organized Project

Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 14 of 91.

challenge icon

Challenge

Easy

Let's build a complete blog application with proper namespace organization, bringing together everything you've learned about namespaces, the use keyword, and PSR-4 autoloading.

You'll create a well-structured project with five files that demonstrate how real PHP applications organize their code:

  • src/Models/Author.php — Define an Author class in the Blog\Models namespace. It should have a public $name property, a constructor that accepts and sets the name, and a getBio() method that returns "Author: [name]".
  • src/Models/Post.php — Define a Post class in the Blog\Models namespace. It should have public $title and public $author properties (where author is an Author object). The constructor accepts a title and an Author object, setting both. Add a getSummary() method that returns "[title] by [author name]".
  • src/Services/Publisher.php — Define a Publisher class in the Blog\Services namespace. It should have a publish(Post $post) method that accepts a Post object and returns "Published: [post title]". You'll need to import the Post class using the use keyword since it's in a different namespace.
  • vendor/autoload.php — Create a PSR-4 autoloader using spl_autoload_register that maps the Blog\ namespace prefix to the src/ directory. This single autoloader handles loading all your classes automatically.
  • index.php — Your entry point. Require the autoloader, then use the use keyword to import Blog\Models\Author, Blog\Models\Post, and Blog\Services\Publisher. Create an Author named "Jane Smith", a Post with title "Getting Started with PHP" using that author, and a Publisher. Print the author's bio, the post's summary, and the result of publishing the post (each on its own line).

Notice how the Publisher service depends on the Post model — this demonstrates how classes in different namespaces can work together by importing what they need with use statements.

Try it yourself

<?php
// Require the autoloader
require_once 'vendor/autoload.php';

// TODO: Import the necessary classes using 'use' statements
// - Blog\Models\Author
// - Blog\Models\Post
// - Blog\Services\Publisher

// TODO: Create an Author named "Jane Smith"

// TODO: Create a Post with title "Getting Started with PHP" using that author

// TODO: Create a Publisher

// TODO: Print the author's bio

// TODO: Print the post's summary

// TODO: Print the result of publishing the post
?>

All lessons in Object Oriented Programming