Search code examples
phpautoloadswiftmailerautoloader

Swift Mailer ruins autolading


I'm writing simple PHP application which is using Swift Mailer library. My app doesn't use namespaces nor composer.

However, after requiring swift_required.php my (model) classes are not found (Fatal error: Class 'Format' not found is thrown by PHP interpret).

Autolading

define("_DOCUMENT_ROOT", str_replace("//", "/", $_SERVER['DOCUMENT_ROOT'] . "/"));
    function __autoload($class_name) {
        $file_name = $class_name . '.php';
        $include_foleder = array("php/model/", "templates/","cron/crons_tasks/");
        foreach ($include_foleder as $folder) {
            $abs_path = _DOCUMENT_ROOT . $folder . $file_name;
            if (file_exists($abs_path)) {
                require_once $abs_path;
            }
        }
    }

Problematic part of function

  $bar = Format::bar($foo); //works fine
  require_once _DOCUMENT_ROOT . "php/lib/swiftmailer-master/lib/swift_required.php"; //works fine
  $bar = Format::bar($foo); //Class not found

Class Format is my custom class, located in _DOCUMENT_ROOT . php/model/Format.php. Also other custom classes (from model folder) after requiring Swift Mailer are not found.

So I guessing that my former autoload is somehow overridden by Swift Mailer, is this possible?

Thank you.


Solution

  • Instead of __autoload(), you should use spl_autoload_register.

    If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.

    http://php.net/manual/en/function.spl-autoload-register.php

    define("_DOCUMENT_ROOT", str_replace("//", "/", $_SERVER['DOCUMENT_ROOT'] . "/"));
    
    spl_autoload_register(function($class_name) {
        $file_name = $class_name . '.php';
        $include_folder = array("php/model/", "templates/","cron/crons_tasks/");
        foreach ($include_folder as $folder) {
            $abs_path = _DOCUMENT_ROOT . $folder . $file_name;
            if (file_exists($abs_path)) {
                require_once $abs_path;
            }
        }
    });