Look at this source code of the plugin Slapper, maybe you'll find what you're wanting to do. https://github.com/PMPlugins/Slapper/tree/php7/Slapper