1

Assume I have a system in PHP that involves class discovery. The result of the class discovery is cached for performance.

Now I had the idea to attempt to clear or invalidate the cache, if the code changes. Either because a developer did something, or because a new version of a 3rd party library was downloaded.

One idea would be to compare file hashes for the class file. But doing this with e.g. md5(file_get_contents($file)) seems rather costly, and not something we want to do in every request / process.

Is there another, faster way to get hash for a PHP class, that produces a different result if the code changes?

I imagine that the answer is no, but one can always ask and hope.

9
  • 1
    You can check out the speed of different hashes and use hash_file. You'd possibly be able to compare modification dates and sizes, too. It's how most FTP programs do it. Commented Jun 25, 2017 at 18:05
  • I haven't looked in the context of your question, but I wonder if you couldn't figure out a way using the the ReflectionClass: php.net/manual/en/class.reflectionclass.php since it is meant for getting info on PHP classes Commented Jun 25, 2017 at 18:07
  • How about just invalidating the cache on deployment? Commented Jun 25, 2017 at 18:11
  • @h2ooooooo Oh great, this is already one step better than md5(file_get_contents()) :) Commented Jun 25, 2017 at 18:21
  • @kjones Yes obviously a ReflectionClass::getClassHash() would do the job, but such a method does not currently exist. Commented Jun 25, 2017 at 18:26

1 Answer 1

1

I think you can use filemtime function to get the last modified of the file instead of checking the content of the file. Sorry if it's not what you want to.

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

3 Comments

It clearly is or can be an improvement over md5(file_get_contents()). It is probably good enough for the majority of cases.
Of course it still means one has to know which file a class was defined in. ReflectionClass::getFileName() can do this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.