Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cookiedev's avatar

PHP For Beginners - refactor

Hi! I've just finished all the 'PHP for beginners' course material released thus far, and it got me thinking about improving the codebase before the next video is released. I'm wondering if I could get some feedback on a refactor I've made recently.

In many cases in the course, we're accessing the database directly from a controller file like so:

 // get the database from the app container 
$db = App::resolve(Database::class);

// query database
$note = $db->query('select * from notes where id = :id', [
    'id' => $_GET['id']
])->findOrFail();

I'm wondering if this could be broken out into its own class for that particular resource, in this example, "Note" like so:

class Note
{
    static function get($id)
    {
        $db = App::resolve(Database::class);

        return $db->query('select * from notes where id = :id', [
            'id' => $id
        ])->findOrFail();
    }
}

Then inside the controller, all I'd have to do if I wanted a note is to call Note::get($id). Would this be considered a decent refactor? Is it wrong that I'm resolving off the app container from my static class method?

0 likes
3 replies
LaryAI's avatar
Level 58

This is a great refactor! It's a good practice to break out code into its own class, especially when it's related to a particular resource.

It's also not wrong to resolve off the app container from a static class method. In fact, this is a common pattern in many frameworks.

You could also consider using dependency injection instead of resolving off the app container. This would allow you to inject the database instance into the Note class, rather than resolving it each time.

class Note
{
    private $db;

    public function __construct(Database $db)
    {
        $this->db = $db;
    }

    public static function get($id)
    {
        return $this->db->query('select * from notes where id = :id', [
            'id' => $id
        ])->findOrFail();
    }
}
1 like
webrobert's avatar

What I like about those courses is they lead up to coding with Laravel. Have you started Laravel 8 from Scratch? In laravel a lot of these refactors that the first beginner php course has inspired for you. You can see (and now understand) in the laravel code base. Oh, and Congrats on finishing it!

1 like
cookiedev's avatar

@webrobert Thank you! Im about to start it, but I'd still like to sharpen my vanilla PHP skills by trying out my own abstractions.

Please or to participate in this conversation.