§ Classes VS Namespaces

11 Feb 2016 | Anton Kril Tweet

Many PHP frameworks use classes as namespaces for functions. The most widespread example is the Controller class:

<?php

class UserController
{
  public function viewAction()
  {
    // Show user
  }
  
  public function removeAction()
  {
    // Remove user
  }
}

Action methods in this class are not related:

If there is a need to group such functions, namespaces should be used instead:

<?php
namespace User;

function view()
{
  // View user
}

function remove()
{
  // Remove user
}

If you need to represent operations but, for some reason (convention), only objects are allowed, you can use classes with a single method (commands):

<?php 
namespace User;

class View
{
  public function __invoke() // or execute()
  {
  }
}

class Remove
{
  public function __invoke()
  {
  }
}