Bright Nucleus Namespace Backtracer
, (*1)
, (*2)
Get the namespace of the calling object, by scanning the debug backtrace, skipping a known set of namespaces & functions in the process., (*3)
Table Of Contents
Overview
This class/trait allows you to traverse the debug_backtrace() to find out what the calling class/function or the calling namespace is. This is useful in cases where you need to find out at runtime in what context a given method was called., (*4)
Installation
The best way to install this package is through Composer:, (*5)
composer require brightnucleus/namespace-backtracer
Basic Usage
Setting Things Up
To create a new class that can fetch the caller's name or namespace, you can either extend the BrightNucleus\NamespaceBacktracer\NamespaceBacktracerClass class or, should you already have a class you need to extend, you can import the BrightNucleus\NamespaceBacktracer\NamespaceBacktracerTrait trait., (*6)
In both cases you'll want to override one or more of the three methods that allow you to adapt the behavior to your environment:, (*7)
This gets the list of interfaces/classes to ignore while traversing the backtrace., (*8)
This gets the list of functions to ignore while traversing the backtrace., (*9)
This defines by what string the global namespace is represented., (*10)
Making The Call
To get the caller's namespace for a specific call, you pass the output of debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) that was executed from within the callee to the getCallingNamespace() method. If you don't provide a debug_backtrace output, it will get fetched within the trait (which might be a different context than the one you want to check)., (*11)
Example:, (*12)
<?php
namespace CalleeNamespace {
use BrightNucleus\NamespaceBacktracer\NamespaceBacktracerTrait;
class Callee {
use NamespaceBacktracerTrait;
protected function getIgnoredInterfaces() {
return [
'CalleeNamespace\Callee',
];
}
public function calledFunctionGetCaller() {
echo $this->getCaller();
}
public function calledFunctionGetNamespace() {
echo $this->getCallingNamespace();
}
}
}
namespace CallerNamespace {
use CalleeNamespace\Callee;
class Caller {
public function callingFunctionGetCaller() {
$callee = new Callee();
$callee->calledFunctionGetCaller();
}
public function callingFunctionGetNamespace() {
$callee = new Callee();
$callee->calledFunctionGetNamespace();
}
}
}
$caller = new CallerNamespace\Caller();
// This will echo "CallerNamespace\Caller" from within the
// CalleeNamespace\Callee\calledFunction() method.
$caller->callingFunctionGetCaller();
// This will echo "CallerNamespace" from within the
// CalleeNamespace\Callee\calledFunction() method.
$caller->callingFunctionGetNamespace();
Contributing
All feedback / bug reports / pull requests are welcome., (*13)
License
Copyright (c) 2016 Alain Schlesser, Bright Nucleus, (*14)
This code is licensed under the MIT License., (*15)