DEV Community

Discussion on: A complete "Live Reload" feature for PHP projects in a single class

Collapse
 
felipperegazio profile image
Felippe Regazio • Edited

Hello Ankush Thakur, thank you for your comment. How this class works:


I think will be a difficult thing to add the Reloader to cli and daemon applications cause it uses a peace of Javascript as Watcher. But i either can se workarounds to this problem.


The current page is any page that call the hotReloader init() method.
Every page will be treated as a single instance for the reloader.
The reloader will then (by default) collect all files related to the page which called it.
The information collected will be:

  • included files
  • css and js files (link and script elements)
  • paths or files added by add() method on the reloader

With this files in hand the reloader will create a md5 hash that will be your current state.
In parallel, the reloader will add a JS script on your page which will assist changes every 1 sec.

If the hash change, a reload will be triggered.
If the css change, it will be replaced on the fly
If a js change, a reload will be triggered

If you have 3 tabs opened and change a file which is related to only one, only this tab will reload. If you change a file which is related to all tabs, than all tabs will reload.

I have been using this class in many projects and i think is stable for while. I tested it with pure php projects and with some frameworks (laravel and cake) and all done well. I added the class to the framework, and added an instance on a "layout" file, so every page inherits the hot reload capabilities.

You can check the sources or documentation on git for details about how it works, and the possible options. There is a simple example on sources too.

Here is the "How it Works" documentation section, i believe will clarify your question:

"This class is divided in two parts: PHP and the Javascript part. The php part will build a list of all files related to your current code (which calls the reloader) and use the datetime or md5_file to create a unique application checksum, this will be the current state of your code. This class adds this checksum (hash) on the headers Etag field of every request. The javascript part keep watching your application headers, scripts and link tags every 1 sec. When something has changed (the etag checksum or any tag related file), the JS will perceive the diff and will reload the page. Of course, many features are included like the ignore lists, watcher increment, error handling, etc. To know more about, please read the source code self documentation on hotreloader.php file".

Any suggestion or doubts, please tell me ; )