0

I have a function that is called many times that look like this:

function attachImagesToProduct(Product $csProduct) {
    $searchPath = realpath(__DIR__ . "/../images");
    $files = scandir($searchPath);
    $files = array_map(function ($file) use ($searchPath) {
        return $searchPath . "/" . $file;
    }, $files);
    
    // Does stuff
}

However, the biggest performance issue is on the scandir + array_map parts. I need to do these only one time. This is why I wanted to mark $files as static, but because they are not constant expressions I can't. Is there any way to mark $files as "lazy-evaluated" static, then I can avoid to do this heavy stuff everytimes I call the function ?

4
  • 2
    Would this help? stackoverflow.com/q/118698/4616087 Commented Jul 11, 2024 at 9:43
  • 2
    static $files = null; if ($files === null) $files = ...; return $files Commented Jul 11, 2024 at 9:47
  • Wouldn't it make more sense to have a separate function to get files and then pass such files as argument? That would also allow things like adding images in batches or using generators to reduce memory footprint. Commented Jul 11, 2024 at 10:47
  • your function is called many times during the same script lifecycle or you need to keep the lazy evaluation beyound the script lifecycle? Commented Jul 11, 2024 at 11:48

1 Answer 1

0

Well, I don't even know why declaring it to null and then initialize it the first time the function is called didn't come to my mind, but it was obviously the simplest way to do it. Here is my solution (I moved it in another function):

function getImageFiles()
{
    $searchPath = realpath(__DIR__ . "/../images");
    static $files = null;

    if ($files == null) {
        $filesList = scandir($searchPath); // TODO: Peut-être lourd ?
        $files = array_map(function ($file) use ($searchPath) {
            return $searchPath . "/" . $file;
        }, $filesList);
        logmessage("Scanned $searchPath for product images");
    }

    return $files;
}

Also, my use-case was that this script is called via c5:exec, and I needed to keep this static variable only for the current script lifecycle. I hope this may help someone else !

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.