Usage
To use the inspector library you can use the inspector service.
$inspector = service('inspector');
With AutoInspect set to true, you don't need to do anything else. Your application will start being inspected automatically.
It's possible by the use of CI4 events functionality. In the post_controller_constructor the code will start a segment, providing the controller as the title and the method's name as the label. Then in the post_system it will end the segment.
You may however need finer grained control over your code points and maybe need to access other more powerful inspector functionality, and this is where the service comes in. Here we present just a few useful methods, check the basic php library documentation for more features.
You can add a segment from anywhere in your code. Assuming you have the getUsers method in your controller:
/*
* gets JSON payload of $limit users
*/
public function getUsers(int $limit)
{
return $inspector->addSegment(function() {
$userModel = new UserModel();
$users = $userModel->findAll($limit);
$this->response->setStatusCode(200, 'OK')->setJSON($users, true)->send();
}, 'getUsers', 'Get Users');
}
You can also report exceptions intentionally:
/*
* Validate the user has the proper age set
*/
public function validateUserAge(): bool
{
try {
if($this->UserAge < 13) {
throw new \UserException\AgeNotAppropriate('Cannot register user, minimum age requirement not met.');
}
} catch (\UserException\AgeNotAppropriate $e) {
$inspectorInstance->reportException($e);
/* Your exception handling code... */
}
}

Using the helper

The helper function provides a shortcut to retrieve an instance of the Inspector service. It must first be loaded using the helper() method or telling your BaseController to always load it.
helper('inspector');
/*
* Get an instance of inspector
*/
$inspector = inspector();
/*
* Add a segment through the helper
*/
inspector(function () {
/* run your code here... */
$asyncData = $this->getAsyncData('https://data.mysite.io');
return $this->startDataSyncJob($asyncData);
}, 'data-load', 'Data Load Flow');
/*
* Add a segment through the instance
*/
$inspector->addSegment(function () {
/* run your code here... */
try {
$asyncData = $this->getAsyncData('https://data.mysite.io');
return $this->startDataSyncJob($asyncData);
} catch(\DataException\DataLoadException $e) {
$inspectorInstance->reportException($e);
}
}, 'data-load', 'Data Load Flow');
/*
* Report an exception
*/
$inspector->reportException(new \Exception('Model Setup Error'));
Due to the shorthand nature of the helper function it can only add a segment or return a service instance.
Copy link