i'm trying to test a simple class. I'm following this tutorial( http://code.tutsplus.com/tutorials/testing-laravel-controllers--net-31456 ).
I have this error, while running tests:
Method Mockery_0_App_Interfaces_MealTypeRepositoryInterface::getValidator() does not exist on this mock object
Im using repository structure. So, my controller calls repository and that returns Eloquent's response.
I'm relatively new in php and laravel. And I've started learning to test a few days ago, so I'm sorry for that messy code.
My test case:
class MealTypeControllerTest extends TestCase
{
public function setUp()
{
parent::setUp();
$this->mock = Mockery::mock('App\Interfaces\MealTypeRepositoryInterface');
$this->app->instance('App\Interfaces\MealTypeRepositoryInterface' , $this->mock);
}
public function tearDown()
{
Mockery::close();
}
public function testIndex()
{
$this->mock
->shouldReceive('all')
->once()
->andReturn(['mealTypes' => (object)['id' => 1 , 'name' => 'jidlo']]);
$this->call('GET' , 'mealType');
$this->assertViewHas('mealTypes');
}
public function testStoreFails()
{
$input = ['name' => 'x'];
$this->mock
->shouldReceive('getValidator')
->once()
->andReturn(Mockery::mock(['fails' => true]));
$this->mock
->shouldReceive('create')
->once()
->with($input);
$this->call('POST' , 'mealType' , $input ); // this line throws the error
$this->assertRedirectedToRoute('mealType.create');//->withErrors();
$this->assertSessionHasErrors('name');
}
}
My EloquentMealTypeRepository:
Nothing really interesting.
class EloquentMealTypeRepository implements MealTypeRepositoryInterface
{
public function all()
{
return MealType::all();
}
public function find($id)
{
return MealType::find($id);
}
public function create($input)
{
return MealType::create($input);
}
public function getValidator($input)
{
return MealType::getValidator($input);
}
}
My eloquent implementation:
Nothing really interresting,too.
class MealType extends Model
{
private $validator;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'meal_types';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [];
public function meals()
{
return $this->hasMany('Meal');
}
public static function getValidator($fields)
{
return Validator::make($fields, ['name' => 'required|min:3'] );
}
}
My MealTypeRepositoryInterface:
interface MealTypeRepositoryInterface
{
public function all();
public function find($id);
public function create($input);
public function getValidator($input);
}
And finally, My controller:
class MealTypeController extends Controller {
protected $mealType;
public function __construct(MealType $mealType)
{
$this->mealType = $mealType;
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$mealTypes = $this->mealType->all();
return View::make('mealTypes.index')->with('mealTypes' ,$mealTypes);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$mealType = new MealTypeEloquent;
$action = 'MealTypeController#store';
$method = 'POST';
return View::make('mealTypes.create_edit', compact('mealType' , 'action' , 'method') );
}
/**
* Validator does not work properly in tests.
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$input = ['name' => $request->input('name')];
$mealType = new $this->mealType;
$v = $mealType->getValidator($input);
if( $v->passes() )
{
$this->mealType->create($input);
return Redirect::to('mealType');
}
else
{
$this->errors = $v;
return Redirect::to('mealType/create')->withErrors($v);
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
return View::make('mealTypes.show' , ['mealType' => $this->mealType->find($id)]);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$mealType = $this->mealType->find($id);
$action = 'MealTypeController#update';
$method = 'PATCH';
return View::make('mealTypes.create_edit')->with(compact('mealType' , 'action' , 'method'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
$mealType = $this->mealType->find($id);
$mealType->name = \Input::get('name');
$mealType->save();
return redirect('mealType');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$this->mealType->find($id)->delete();
return redirect('mealType');
}
}
That should be everything. It's worth to say that the application works, just tests are screwed up.
Does anybody know, why is that happening? I cant see a difference between methods of TestCase - testIndex and testStoreFails, why method "all" is found and "getValidator" is not.
I will be thankful for any tips of advices.
Perhaps an aside, but directly relevant to anyone finding this question by its title:
If:
You are getting the error BadMethodCallException: Method Mockery_0_MyClass::myMethod() does not exist on this mock object, and
none of your mocks are picking up any of your subject's methods, and
your classes are being autoloaded, (e.g. using composer)
then before making your mock object, you need to force the loading of that subject, by using this line of code:
spl_autoload_call('MyNamespace\MyClass');
Then you can mock it:
$mock = \Mockery::mock('MyNamespace\MyClass');
In my PHPUnit tests, I often put that first line into the setUpBeforeClass() static function, so it only gets called once and is isolated from tests being added/deleted. So the Test class looks like this:
class MyClassTest extends PHPUnit_Framework_TestCase {
public static function setUpBeforeClass() {
parent::setUpBeforeClass();
spl_autoload_call('Jodes\MyClass');
}
public function testIt(){
$mock = \Mockery::mock('Jodes\MyClass');
}
}
I have forgotten about this three times now, each time spending an hour or two wondering what on earth the problem was!
I have found a source of this bug in controller.
calling wrong
$v = $mealType->getValidator($input);
instead of right
$v = $this->mealType->getValidator($input);
Related
I have a Service which is called inside a Controller in a Laravel application. Usually these services are implemented using a composition pattern, where the service is injected in the __construct of the controller; then, whenever it's necessary to use the service, you just call the service and the method you want. If you want to create a new register on the database, you just need to call the service, the method, and pass the necessary parameters to that method.
But let's say I don't want to pass parameters. I want an immutable, zero-parameter object. I have tried to implement this in the code bellow (first there's the service and then the controller where the service is called). Notice I have all the parameters I'd need to pass to each method in the constructor of my service. This produces what I want: an immutable, zero-parameter object.
But there's a problem: it's not in every call of the service that I need all the parameters in the constructor (not every method used needs them), that's why they're typed as a [any type]|null. This seems wrong, because if I don't need all the parameters to construct my object, maybe it should be another object altogether. I don't have a problem with small classes (I like it, actually), but it seems just too much to have a CreateCmsUserService, UpdateCmsUserService, DeleteCmsUserService.
I'd like to know if there's an elegant solution for this constructor with null or if the only way to go is dividing the class.
<?php
namespace App\Services;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\Hash;
use App\Interfaces\CRUD;
class CmsUsersService implements CRUD
{
private ?int $user_id;
private ?array $data;
private ?string $users_to_be_deleted;
public function __construct(?array $data, ?int $user_id, ?string $users_to_be_deleted)
{
$this->user_id = $user_id;
$this->data = $data;
$this->users_to_be_deleted = $users_to_be_deleted;
}
public function create()
{
$this->data['token'] = Hash::make($this->data['email']);
$this->data['password'] = Hash::make($this->data['password']);
User::create($this->data);
return cms_response(trans('cms.users.success_create'));
}
public function update()
{
try {
if (array_key_exists('password', $this->data)) {
$this->data['password'] = Hash::make($this->data['password']);
}
$user = $this->__findOrFail();
$user->update($this->data);
return cms_response(trans('cms.users.success_update'));
} catch (\Throwable $th) {
return cms_response($th->getMessage(), false, 400);
}
}
public function delete()
{
User::whereIn('id', json_decode($this->users_to_be_deleted))->delete();
return cms_response(trans('cms.users.success_delete'));
}
private function __findOrFail()
{
$user = User::find($this->user_id);
if ($user instanceof User) {
return $user;
}
throw new Exception(trans('cms.users.error_user_not_found'));
}
}
<?php
namespace App\Http\Controllers\Cms;
use App\Http\Controllers\Controller;
use App\Http\Requests\UserRequest;
use App\Services\CmsUsersService;
use Illuminate\Http\Request;
class UsersController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(UserRequest $request)
{
$users_service = new CmsUsersService($request->all(), null, null);
$result = $users_service->create();
return redirect()->back()->with('message', $result);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(UserRequest $request, $id)
{
$users_service = new CmsUsersService($request->all(), $id, null);
$result = $users_service->update();
return redirect()->back()->with('message', $result);
}
/**
* Remove the specified resource from storage.
*
* #param string $users_id
* #return \Illuminate\Http\Response
*/
public function destroy($users_id)
{
$users_service = new CmsUsersService(null, null, $users_id);
$result = $users_service->delete();
return redirect()->back()->with('message', $result);
}
}
You could give parameters a default value, like so:
public function __construct(?array $data = [], ?int $user_id = null, ?string $users_to_be_deleted = null)
{
$this->user_id = $user_id;
$this->data = $data;
$this->users_to_be_deleted = $users_to_be_deleted;
}
Now you can use this:
$users_service = new CmsUsersService();
See: https://3v4l.org/InkBY
I'm currently working with one of my friends on making a portfolio for all of his projects and as strangely as it seems, I cannot manage to make setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Class Namespace') working on his code while it is working on my projects.
Here is the error returned by PHP :
!(https://cdn.discordapp.com/attachments/525023910698156034/583938068311179265/unknown.png)
Here is the class Entity which contains the __construct() function and the hydration() function :
<?php
namespace App\Entity;
class Entity {
public function __construct(array $array) {
$this->hydrate($array);
}
public function hydrate($array) {
foreach ($array as $key => $value) {
$setter = 'set' . ucfirst($key);
if (method_exists($this, $setter)) {
$this->$setter($value);
}
}
}
}
Then, here is the Project Class which implements the class Entity :
<?php
namespace App\Entity;
class Project extends Entity implements \JsonSerializable {
private $_title;
private $_description;
private $_imagePath;
private $_link;
private $_repoLink;
private $_creationDate;
public function jsonSerialize() {
return [
'title' => $this->_title,
'description' => $this->_description,
'imagePath' => $this->_imagePath,
'link' => $this->_link,
'repoLink' => $this->_repoLink,
'creationDate' => $this->_creationDate,
];
}
/
* #return string
*/
public function getTitle(): string {
return $this->_title;
}
/
* #param string $title
*/
public function setTitle(string $title) {
$this->_title = $title;
}
/
* #return string
*/
public function getDescription(): string {
return $this->_description;
}
/
* #param string $description
*/
public function setDescription(string $description) {
$this->_description = $description;
}
/
* #return string
*/
public function getImagePath(): string {
return $this->_imagePath;
}
/
* #param string $imagePath
*/
public function setImagePath(string $imagePath) {
$this->_imagePath = $imagePath;
}
/
* #return string
*/
public function getLink(): string {
return $this->_link;
}
/
* #param string $link
*/
public function setLink(string $link) {
$this->_link = $link;
}
/
* #return string
*/
public function getRepoLink(): string {
return $this->_repoLink;
}
/
* #param string $repoLink
*/
public function setRepoLink(string $repoLink) {
$this->_repoLink = $repoLink;
}
/
* #return \DateTime
*/
public function getCreationDate(): \DateTime {
return $this->_creationDate;
}
/
* #param string $creationDate
*/
public function setCreationDate(string $creationDate) {
$this->_creationDate = new \DateTime($creationDate);
}
}
And finally, here is the SQL request :
<?php
namespace App\Model;
class ProjectManager extends Manager {
/**
* return a collection of Project objects
* #return Project[]
* #throws \Exception
*/
public function getProjects() {
$db = $this->getDb();
$q = $db->query(
'SELECT id,
title,
description,
image_path AS imagePath,
link,
repo_link AS repoLink,
creation_date AS creationDate
FROM my_website_projects
ORDER BY creationDate'
);
$q->setFetchMode(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, 'App\Entity\Project');
$projects = $q->fetchAll();
return $projects;
}
}
The only thing that seems to work is to add PDO::FETCH_ASSOC in the fetchAll() but then it doesn't return an object but an array....
Your help would be much appreciated on this problem ! :)
As far as I know, there is no solution to this problem. There is no fetch mode that creates an object passing the returned row as a constructor parameter.
So I would change the code to this a bit clumsy but working solution
public function getProjects() {
$db = $this->getDb();
$q = $db->query(
'SELECT id,
title,
description,
image_path AS imagePath,
link,
repo_link AS repoLink,
creation_date AS creationDate
FROM my_website_projects
ORDER BY creationDate'
);
$projects = [];
while($row = $q->fetch(PDO::FETCH_ASSOC)) {
$projects[] = new App\Entity\Project($row);
}
return $projects;
}
Your mistake is that you slightly confused the way PDO creates objects.
This way is rather blunt, PDO just takes an object and fills it properties, the process is not much different from filling an associative array.
So now you can tell how did your other code work:
first, the constructor parameter in your other class is optional, it means PHP won't complain for it.
second, in your other class properties are spelled equal to column names in the database, and PDO happily fills them as described above.
So, as another solution you can fix these 2 issues: make the constructor parameter optional and remove the underscore from the property names.
Some time ago I wrote an article on fetching obejects with PDO, you may find it useful.
PHP with Symfony framework:
First of all before the context:
My input form is being built by form builder. Nothing is wrong there. So that is not the problem
I am making a sms validator system. I have a controller, and 2 services(validatorservice, smsapi(for api call)) Now my validatorservice looks like this:
class ValidatorService
{
public function validate($telefoonnummer)
{
$pregpatternNL = '(^\+[0-9]{2}|^\+[0-9]{2}\(0\)|^\(\+[0-9]{2}\)\(0\)|^00[0-9]{2}|^0)([0-9]{9}$|[0-9\-\s]{10}$)';
if (!preg_match($pregpatternNL, $telefoonnummer)) {
return false;
} else {
return true;
}
}
}
Then my homecontroller:
use App\Service\ValidatorService;
class HomeController extends AbstractController
{
/** #var SmsApi */
private $smsApi;
/** #var validatorService */
private $validatorService;
public function __construct1(SmsApi $smsApi, Validatorservice
$validatorService)
{
$this->smsApi = $smsApi;
$this->validatorService = $validatorService;
}
/**
* #Route("/")
* #Template()
*
* #param Request $request
*
* #return array
*/
public function indexAction(Request $request)
{
$form = $this->createForm(
SmsLogFormType::class,
new SmsLog(),
[
'method' => 'post',
]
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** #var SmsLog $smslog */
$formData = $form->getData();
try {
$telefoonnummer = $formData->getTel();
$telefoonnummer = preg_replace('/[^0-9]/', '', $telefoonnummer);
$validatorservices = $this->validatorService-
>validate($telefoonnummer);
if ($validatorserviceres === false) {
$this->addFlash(
'notice',
'telefoonnummer onjuist formaat'
);
exit;
} else {
blablabla
}
Now whatever i try i get the error :
Call to a member function validate() on null
At first i thought maybe its something with the constructor names, but found online that that doesn't matter at all (also i didn't receive any code errors there)
Then i tried adding echo's to the if statement in my service. Maybe return true or false is seen as null but this doesn't work either.
I guess it's because of the number of arguments per constructor. If you define multiple constructors for a class, they should have different argument counts.
What you could do instead is to check whether or not the object you received is part of the wanted class/classes.
Or create static functions that instatiate the class with different object types.
EDIT
Use the default autowiring mechanisms:
private $smsApi;
private $validatorService;
public function __construct(SmsApi $smsApi, ValidatorService $validatorService)
{
$this->smsApi = $smsApi;
$this->validatorService = $validatorService;
}
It should work as intended if you change your Code to this :
/** #var SmsApi */
private $smsApi;
private $validatorService;
public function __construct(SmsApi $smsApi, ValidatorService $validatorService)
{
$this->validatorService = $validatorService;
$this->smsApi = $smsApi;
}
__construct1 and __construct2 are not native functions of php, so when the class is loaded, the constructors are not invoking and validatorService/smsApi are not being set (so they are null). The native function is called __construct.
/** #var SmsApi */
private $smsApi;
private $validatorService;
public function __construct(SmsApi $smsApi, ValidatorService $validatorService)
{
$this->smsApi = $smsApi;
$this->validatorService = $validatorService;
}
Or if doest not work, inject the services as arg in
public function indexAction(Request $request)
so...
public function indexAction(Request $request,SmsApi $smsApi, ValidatorService $validatorService)
and use $validatorService->validate();
Is there any option to inform PhpStorm that method which it says that not exist, is beyond his scope and is defined somewhere else ?
In simpler words:
I have method execution:
Db::transactional($this)->transactionalUpdate($result);
I have got method definition also:
public function transactionalUpdate(ImportantObjectButNotMuch $baconWithButter)
{
echo 'Do a lot of tricks...';
}
Unfortunately PhpStorm doesn't know that execution : ->transactionalUpdate($result); should run public function transactionalUpdate.
Is there any option to write PhpDoc or some other tag to inform it that in case of name refactorization it should change the original function name too ?
P.S. My class structure looks like this:
class Db
{
public static function transactional($object)
{
return TransactionalProxy::newInstance($object); //3. It returns ApiObject object
}
}
class ApiObject
{
public function update_record()
{
//1. I am starting from there
$result = new ImportantObjectButNotMuch();
Db::transactional($this)->transactionalUpdate($result); //2. Next i am passing $this to Db class, to transactional method //4. It should run below transactionalUpdate method
}
public function transactionalUpdate(ImportantObjectButNotMuch $baconWithButter)
{
echo 'Do a lot of tricks...'; //5. It ends there, it is working but PhpStorm doesn't see it
}
}
EDIT AFTER ANSWER:
#Nukeface and #Dmitry caused me to come up with the answer on my Question:
Lets see again into my files structure:
class Db
{
public static function transactional($object)
{
return TransactionalProxy::newInstance($object); //3. It returns ApiObject object
}
}
class ApiObject
{
public function update_record()
{
//1. I am starting from there
$result = new ImportantObjectButNotMuch();
//EDIT//Db::transactional($this)->transactionalUpdate($result); //2. Next i am passing $this to Db class, to transactional method //4. It should run below transactionalUpdate method
/** #var self $thisObject */
//Line above informs PhpStorm that $thisObject is ApiObject indeed
$thisObject = Db::transactional($this)
$thisObject->transactionalUpdate($result);
}
public function transactionalUpdate(ImportantObjectButNotMuch $baconWithButter)
{
echo 'Do a lot of tricks...'; //5. It ends there, it is working but PhpStorm doesn't see it
}
}
You should make use of Typehints. Updated your code below:
/**
* Class Db
* #package Namespace\To\Db
*/
class Db
{
/**
* #param $object
* #return ApiObject (per your line comment)
*/
public static function transactional($object)
{
return TransactionalProxy::newInstance($object); //3. It returns ApiObject object
}
}
/**
* Class ApiObject
* #package Namespace\To\ApiObject
*/
class ApiObject
{
/**
* #return void (I see no "return" statement)
*/
public function update_record()
{
//1. I am starting from there
$result = new ImportantObjectButNotMuch();
Db::transactional($this)->transactionalUpdate($result); //2. Next i am passing $this to Db class, to transactional method //4. It should run below transactionalUpdate method
}
/**
* #param ImportantObjectButNotMuch $baconWithButter
* #return void
*/
public function transactionalUpdate(ImportantObjectButNotMuch $baconWithButter)
{
echo 'Do a lot of tricks...'; //5. It ends there, it is working but PhpStorm doesn't see it
}
}
You can quickly create basic docblocks and typehints by typing /** then pressing either "enter" or "space". Enter if you want a docblock and space if you want a typehint.
Examples of own code below:
/**
* Class AbstractEventHandler
* #package Hzw\Mvc\Event
*/
abstract class AbstractEventHandler implements EventManagerAwareInterface
{
/**
* #var EventManagerInterface
*/
protected $events;
/**
* #var EntityManager|ObjectManager
*/
protected $entityManager;
/**
* AbstractEvent constructor.
* #param ObjectManager $entityManager
*/
public function __construct(ObjectManager $entityManager)
{
$this->setEntityManager($entityManager);
}
/**
* #param EventManagerInterface $events
*/
public function setEventManager(EventManagerInterface $events)
{
$events->setIdentifiers([
__CLASS__,
get_class($this)
]);
$this->events = $events;
}
/**
* #return EventManagerInterface
*/
public function getEventManager()
{
if (!$this->events) {
$this->setEventManager(new EventManager());
}
return $this->events;
}
/**
* #return ObjectManager|EntityManager
*/
public function getEntityManager()
{
return $this->entityManager;
}
/**
* #param ObjectManager|EntityManager $entityManager
* #return AbstractEventHandler
*/
public function setEntityManager($entityManager)
{
$this->entityManager = $entityManager;
return $this;
}
}
In the above example, PhpStorm knows what every function requires and returns. It knows the types and as some "return $this" it knows about the possibility to chain functions.
As an addition, the above code example uses only "docblocks". Below some "inline typehints" from within a function. Especially useful when it's not going to be immediately clear what is going to be returned. That way, again, PhpStorm knows from where to get functions, options, etc. to show you.
/** #var AbstractForm $form */
$form = $this->getFormElementManager()->get($formName, (is_null($formOptions) ? [] : $formOptions));
/** #var Request $request */
$request = $this->getRequest();
As a final hint. If you create a bunch of properties for a class, such as in my example protected $events or protected $entityManager, you can also generate the getters & setters. If your properties contain the docblocks, it will also generate the docblocks for you on these functions.
E.g. the property below
/**
* #var EntityManager|ObjectManager
*/
protected $entityManager;
When using "Alt + Insert" you get a menu at cursor location. Choose "Getters/Setters". In the pop-up, select "entityManager" and check the box at the bottom for "fluent setters". Then the code below is generated for you:
/**
* #return ObjectManager|EntityManager
*/
public function getEntityManager()
{
return $this->entityManager;
}
/**
* #param ObjectManager|EntityManager $entityManager
* #return AbstractEventHandler
*/
public function setEntityManager($entityManager)
{
$this->entityManager = $entityManager;
return $this;
}
The closes thing you can do to what you want to do is to use #return with multiple types.
/**
* #param $object
* #return ApiObject|AnotherApiObject|OneMoreApiObject
*/
public static function transactional($object)
{
return TransactionalProxy::newInstance($object);
}
I'm having some troubles getting a piece of code to work in laravel. I have a SecuredEloquent class that all my 'secured' models extend. what it does is simply add a whereHas clause to the query in the newQuery function I override:
class SecuredEloquent extends Eloquent
{
public function newQuery($excludeDeleted = true)
{
$query = parent::newQuery($excludeDeleted);
$context = App::make('Wall\Context\Context');
$query->whereHas('permissions', function($q) use ($context)
{
$q->where('context_id','=',$context->id());
$q->where('level','>=', $context->level());
});
return $query;
}
}
The problem: it doesn't work. I get "The connection was reset" errors in my browser and nothing in the log :( anyone any idea what I'm doing wrong?
edit2:
MyModel extends SecuredEloquent, OtherModel doesn't
When I try to run it in artisan tinker nothing happens.
var_dump(MyModel::all()); simply stops the process (it crashes? no idea, again nothing logged, it simply quits)
var_dump(OtherModel::all()); however simply works
edit:
I have ContextServiceProvider:
use Illuminate\Support\ServiceProvider;
class ContextServiceProvider extends ServiceProvider
{
/**
* Register
*/
public function register()
{
$this->app->singleton('Wall\Context\Context', function($app)
{
return new AppContext;
});
}
}
with AppContext:
use Illuminate\Database\Eloquent\Model;
class AppContext
{
/**
* The current context
*
* #var Illuminate\Database\Eloquent\Model
*/
protected $context;
/**
* The current context level
*
* #var int
*/
protected $level;
/**
* Check to see if the context has been set
*
* #return boolean
*/
public function has()
{
if($this->context) return true;
return false;
}
/**
* Get the context identifier
*
* #return integer
*/
public function id()
{
if ( $this->has() ) return $this->context->id;
return 0;
}
/**
* Get the context permission leven
*
* #return string
*/
public function level()
{
if ( $this->level ) return $this->level;
return 1;
}
}
Hope this helps