Best practice: Where to store your own code and include in autoloader


#1

Hi,

I didn’t find any documentation on this, will happily write it.
For a start I had all my classes in one file and just included that file. Now its time to manage this properly, put each class in an own file, and custom template files as well.

My idea is to not touch the vendor directory at all, e.g. having all my self-written classes in /src, all self-written templates in /templates.

But of course I want to avoid having to include a lot of class files at the top of each script but get them trough the autoloader. I found this promising article on the composer autoloader, is that the ATK way to do it?

Best regards
Philipp


#2

Specifying your namespace in composer.json is the best way to go. I haven’t touched on that, as it is technically outside of ATK scope.


#3

Hi,

here is an example of composer.json:

{
  "require":{
    "atk4/ui": "^1.2",
    "phpmailer/phpmailer": "~6.0"
  }
  ,
  "autoload":{
    "psr-4":{
      "Pmg\\":"src/"
    }
  }
}

In this case, my own classes are stored in /src, their namespace is Pmg.

After adding your custom class folder to the autoloader, it has to be regenerated using console:

composer dump-autoload -o

Afterwards, your own classes can be used like in my case:

$class = new \Pmg\Class.php

Best regards
Philipp


#4

And because you’re using PSR4, then it will treat your namespaces as subfolders.

For example,

namespace Pmg\My\space;
class My_Cool_Class {}

// should be saved in
// src/My/space/My_Cool_Class.php file