itsgoingd / clockwork

Clockwork - php dev tools in your browser - server-side component
https://underground.works/clockwork
MIT License
5.68k stars 321 forks source link

How to use the timeline() functionality in Slimphp #463

Closed seanhamlin closed 3 years ago

seanhamlin commented 3 years ago

Hi there,

I am integrating Clockwork into a mid sized Slimphp 4.7.1 app that I look after. I have added the middleware, and have got the base functionality working with the chrome extension.

image

I now want to add additional events to the timeline, to help better visualise the major areas where the app is spending its time. e.g. Guzzle requests to third party APIs, loading data from files etc.

Reading the docs

clock()->event("Loading user's latest tweets via Twitter API")->start();
clock()->event("Loading user's latest tweets via Twitter API")->end();

This simply yields

Call to undefined function clock()

If I manually require the helpers file

require_once '../vendor/itsgoingd/clockwork/Clockwork/Support/Vanilla/helpers.php';

This does not return the actual clockwork instance

Call to a member function event() on null

Anyone know how to get the clockwork instance from the middleware in Slimphp 4?

itsgoingd commented 3 years ago

Hey,

Looks like this is not documented, but you can pass your own pre-configured Clockwork instance instead of the metadata path to the middleware, like this:

$app = AppFactory::create();
$app->add(new Clockwork\Support\Slim\ClockworkMiddleware($app, $clockwork));

Now to create a simple Clockwork instance we can take inspiration from how the middleware does it:

$clockwork = new Clockwork\Clockwork();

$clockwork->storage(new Clockwork\Storage\FileStorage($storagePath));
$clockwork->authenticator(new Clockwork\Authentication\NullAuthenticator);

At this point you will have a reference to the Clockwork instance, which you can use to add timeline events, log messages, etc.:

$clockwork->event("Loading user's latest tweets via Twitter API")->start();
$clockwork->error('Something is not right.');

It might also be a good idea to register this instance with a dependency-injection container if you use one or to create your own clock() helper.

seanhamlin commented 3 years ago

Thanks @itsgoingd, that makes sense.

$container->set('clockwork', function() {
  $clockwork = new Clockwork();
  $clockwork->storage(new FileStorage(getenv('TEMP_FOLDER') . '/clockwork'));
  $clockwork->authenticator(new NullAuthenticator);
  return $clockwork;
});
$app->add(new ClockworkMiddleware($app, $container->get('clockwork')));

This was what I ended up doing in the index.php file, and it works a charm.