简体   繁体   中英

Composer execute script after calling autoload.php

I'm writing a composer package that needs to execute a list of safety checks when Composer autoload.php is called and before accessing its classes and methods

I have this composer.json file:

{
    "name": "def-studio/logger",
    "description": "Def Studio logger system",
    "type": "library",
    "require": {
        "php": ">=5.3.0"
    },
    "license": "MIT",
    "autoload": {
        "psr-4": {
            "DefStudio\\Logger\\": "src/"
        }
    }
}

After ./vendor/autoload.php is called and the main class DefStudio\\Logger\\Logger.php is loaded, I need to execute this method: Logger::perform_checks() everytime the class is loaded.

my code is, actually:

include_once './vendor/autoload.php';
use DefStudio\Logger\Logger;
Logger::perform_checks();


try{
   //random messy code here
}catch(Exception $ex){
   Logger::error("error!", $ex);
}

I need my package to call Logger::perform_checks() everytime autoload.php is called and I don't want to rely on the user to remember to call it.. I wish it to be automagically called when autoload.php is invoked

Is there any way to automatically execute a php script when autoload.php is called?

Thanks to Dejv comment, I found a useful answer in the question linked from him:

Updated my package composer.json file in order to add a script to be executed on autoload:

{
    "name": "def-studio/logger",
    "description": "Def Studio logger system",
    "type": "library",
    "require": {
        "php": ">=5.3.0"
    },
    "license": "MIT",
    "autoload": {
        "psr-4": {
            "DefStudio\\Logger\\": "src/"
        }
        "files": ["src/utilities/autoloader.php"]
    }
}

and in autoloader.php I executed my checks and startup code

this way, when the developer calls include_once './vendor/autoload.php' , my code is executed as well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM