While working with a small side-project, I noticed that working with autoloading namespaced classes with F3 can be a bit hacky if you are not using composer. This is probably because F3 is designed keeping in mind how composer works. Since composer wasn’t used for my particular purpose, the conventional way didn’t work as it was supposed to.

F3’s autoloader is ‘basic’. It doesn’t provide the complex autoloading features composer uses. This makes sense because F3 “doesn’t get in your way”. People starting out with PHP might find it easier. When you add AUTOLOAD to any config files, F3 adds the classes found inside the directory. For example,

$f3->set('AUTOLOAD','app/controllers/;vendors/twitteroauth/src/');

This adds couple of directories to be autoloaded, app/controllers/ and vendors/twitteroauth/src (I am using Abraham’s Twitter OAuth library here). There are two things I learned on the way:

  1. AUTOLOAD adds only classes inside the directories.
  2. Autoloaded directives should only be paths. So, app/controllers/autload.php won’t work if declared inside AUTOLOAD directive.

While adding namespaced classses, you need to create directories that mimic the namespace. For example, Abraham’s OAuth plugin classes start with:

namespace Abraham\TwitterOAuth;
class TwitterOAuth extends Config
{
...
}

So, I needed the created two directories, Abraham and TwitterOAuth and put the classes inside it. So, now my directory structure looks like this:

vendors/twitteroauth/src/
└── Abraham
    └── TwitterOAuth
        ├── cacert.pem
        ├── Config.php
        ├── Consumer.php
        ├── HmacSha1.php
        ├── Request.php
        ├── Response.php
        ├── SignatureMethod.php
        ├── Token.php
        ├── TwitterOAuthException.php
        ├── TwitterOAuth.php
        ├── Util
        │   └── JsonDecoder.php
        └── Util.php

With this, my autloaded directive works as expected and loads all the classes. You can read more about it here on StackOverflow

(This post is more like a note-to-self since I tend to forget the quirks.)

A very complicated simple person. Jack of all trades, master of a few. Loves to read books and well-written code. Fluently speaks several languages including JavaScript, PHP, Java, English, Bengali etc. Listens to loads of music everyday. PhD in mood-swing. Chess Grandmaster of disaster.

Leave a Reply

Your email address will not be published. Required fields are marked *