I'm trying to return an object from my Laravel api routes, but all that's returned is an empty array.
My model looks like this:
class MobilePageStats extends Model
{
//
private $score;
private $mobileFriendly;
private $numberRobotedResources;
private $numberTransientFetchFailureResources;
private $transientFetchFailureUrls;
private $cms;
private $ruleResults;
/**
* MobilePageStats constructor.
* #param int $score
* #param bool $mobileFriendly
* #param int $numberRobotedResources
* #param int $numberTransientFetchFailureResources
* #param array $transientFetchFailureUrls
* #param string $cms
* #param array $ruleResults
*/
public function __construct(
$score,
$mobileFriendly,
$numberRobotedResources,
$numberTransientFetchFailureResources,
$transientFetchFailureUrls,
$cms,
$ruleResults
) {
$this->score = $score;
$this->mobileFriendly = $mobileFriendly;
$this->numberRobotedResources = $numberRobotedResources;
$this->numberTransientFetchFailureResources = $numberTransientFetchFailureResources;
$this->transientFetchFailureUrls = $transientFetchFailureUrls;
$this->cms = $cms;
$this->ruleResults = $ruleResults;
}
And I also got getters on everything.
I set all the data in my controller with the constructor, in this function:
public function getData() {
$cms = "";
$score = $this->data->ruleGroups->USABILITY->score;
$mobileFriendly = $this->data->ruleGroups->USABILITY->pass;
if(isset($this->data->pageStats->numberRobotedResources)){
$numberRobotedResources = $this->data->pageStats->numberRobotedResources;
}else{
$numberRobotedResources = '';
}
if(isset($this->data->pageStats->numberTransientFetchFailureResources)){
$numberTransientFetchFailureResources = $this->data->pageStats->numberTransientFetchFailureResources;
}else{
$numberTransientFetchFailureResources = '';
}
if(isset($this->data->pageStats->transientFetchFailureUrls)){
$transientFetchFailureUrls = $this->data->pageStats->transientFetchFailureUrls;
}else{
$transientFetchFailureUrls = '';
}
if(isset($this->data->pageStats->cms)){
$cms = $this->data->pageStats->cms;
if($cms != 'WORDPRESS' && $cms != 'JOOMLA'){
$cms = $this->checkCMS();
}
}
$cvp = $this->getConfigureViewport();
$fontSizes = $this->getUseLegibleFontSizes();
$avoidPlugins = $this->getAvoidPlugins();
$sizeToViewport = $this->getSizeContentToViewport();
$tapTargets = $this->getSizeTapTargetsAppropriately();
$ruleResults = [$cvp, $fontSizes, $avoidPlugins, $sizeToViewport, $tapTargets];
$mobilePageStats = new MobilePageStats($score, $mobileFriendly, $numberRobotedResources,
$numberTransientFetchFailureResources, $transientFetchFailureUrls, $cms, $ruleResults);
return $mobilePageStats;
}
In my API routes I then try to return the model like this:
Route::get('/mobilePageSpeed', function(Request $request){
$data = new PageSpeedMobileController($request->url);
return response($data->getData());
});
But all I get returned when I make the request is:
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;">[]</pre>
</body>
Why is the object not returned? I know it contains data, because I can print it. But can't send it?
I have tried both repsonse()->json($data->getData()); And json_encode($data->getData()), but they give me the same result? I just can't seem to find a solution that works.
So how do I return objects from Laravel Api?
The answer would be to json_encode every single object after you cast them to arrays. Should work :)
You override the original Model constructor with your version, the model is not filled with attributes nor booted.
I dunno what you want to achieve but if you extends a class from Eloquent\Model you cannot override is own costructor without calling the original one, i.e.:
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
Related
I am using a library, and it has the following process to attach many operations to one event:
$action = (new EventBuilder($target))->addOperation($Operation1)->addOperation($Operation2)->addOperation($Operation3)->compile();
I am not sure how to dynamically add operations depending on what I need done.
Something like this
$action = (new EventBuilder($target));
while (some event) {
$action = $action->addOperation($OperationX);
}
$action->compile();
I need to be able to dynamically add operations in while loop and when all have been added run it.
Your proposed solution will work. The EventBuilder provides what is known as a Fluent Interface, which means that there are methods that return an instance of the builder itself, allowing you to chain calls to addOperation as many times as you want, then call the compile method to yield a result. However you are free to ignore the return value of addOperation as long as you have a variable containing an instance of the builder that you can eventually call compile on.
Take a walk with me...
// Some boilerplate classes to work with
class Target
{
private ?string $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function getName(): string
{
return $this->name;
}
}
class Operation
{
private ?string $verb;
public function __construct(string $verb)
{
$this->verb = $verb;
}
public function getVerb(): string
{
return $this->verb;
}
}
class Action
{
private ?Target $target;
private array $operations = [];
public function __construct(Target $target, array $operations)
{
$this->target = $target;
$this->operations = $operations;
}
/**
* Do the things
* #return array
*/
public function run(): array
{
$output = [];
foreach ($this->operations as $currOperation)
{
$output[] = $currOperation->getVerb() . ' the ' . $this->target->getName();
}
return $output;
}
}
Here is a basic explanation of what your EventBuilder is doing under the covers:
class EventBuilder
{
private ?Target $target;
private array $operations = [];
public function __construct(Target $target)
{
$this->target = $target;
}
/**
* #param Operation $operation
* #return $this
*/
public function addOperation(Operation $operation): EventBuilder
{
$this->operations[] = $operation;
// Fluent interface - return a reference to the instance
return $this;
}
public function compile(): Action
{
return new Action($this->target, $this->operations);
}
}
Let's try both techniques and prove they will produce the same result:
// Mock some operations
$myOperations = [
new Operation('Repair'),
new Operation('Clean'),
new Operation('Drive')
];
// Create a target
$target = new Target('Car');
/*
* Since the EventBuilder implements a fluent interface (returns an instance of itself from addOperation),
* we can chain the method calls together and just put a call to compile() at the end, which will return
* an Action instance
*/
$fluentAction = (new EventBuilder($target))
->addOperation($myOperations[0])
->addOperation($myOperations[1])
->addOperation($myOperations[2])
->compile();
// Run the action
$fluentResult = $fluentAction->run();
// Traditional approach, create an instance and call the addOperation method as needed
$builder = new EventBuilder($target);
// Pass our mocked operations
while (($currAction = array_shift($myOperations)))
{
/*
* We can ignore the result from addOperation here, just keep calling the method
* on the builder variable
*/
$builder->addOperation($currAction);
}
/*
* After we've added all of our operations, we can call compile on the builder instance to
* generate our Action.
*/
$traditionalAction = $builder->compile();
// Run the action
$traditionalResult = $traditionalAction->run();
// Verify that the results from both techniques are identical
assert($fluentResult == $traditionalResult, 'Results from both techniques should be identical');
// Enjoy the fruits of our labor
echo json_encode($traditionalResult, JSON_PRETTY_PRINT).PHP_EOL;
Output:
[
"Repair the Car",
"Clean the Car",
"Drive the Car"
]
Rob Ruchte thank you for detailed explanation, one thing I did not include was that each operation itself had ->build() call and I needed to move that to each $builder for it to work.
i have created a joomla component and when i click on publish and unpublish button in admin then i am getting such error.
Fatal error: Call to a member function publish() on boolean in ...\libraries\legacy\controller\admin.php on line 209
Please help
UPDATE
my View.html.php
require_once JPATH_COMPONENT . '/helpers/lab.php';
class labViewStructurelist extends JViewLegacy
{
protected $structurelist;
protected $pagination;
public $filterForm;
public $activeFilters;public $state;
public function display($tpl = null)
{
$this->structurelist = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->state = $this->get('State');
//print_r($this->pagination->pagesTotal);die();
$this->filterForm = $this->get('FilterForm');
$this->activeFilters = $this->get('ActiveFilters');
$this->addToolBar();
$this->sidebar = JHtmlSidebar::render();
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
return parent::display($tpl);
}
protected function addToolBar() {
JToolBarHelper::title( JText::_('COM_LAB_LAB_DDDD'), 'generic.png' );
JToolBarHelper::publish('Structurelist.publish');
JToolBarHelper::unpublish('Structurelist.unpublish');
JToolBarHelper::deleteList('', 'patients.delete', 'JTOOLBAR_DELETE');
JToolBarHelper::preferences('com_lab');
}
}
Controller/stricturelist.php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla controller library
jimport('joomla.application.component.controlleradmin');
class LabControllerStructurelist extends JControllerAdmin
{
public function getModel($name='Structurelist',$prefix='ssModel',$config=array('ignore_request'=>true))
{
$model=parent::getModel($name,$prefix,$config);
return $model;
}
}
models\structurelist.php
defined('_JEXEC') or die;
jimport('joomla.application.component.modellist');
JFormHelper::loadFieldClass('list');
class LabModelStructurelist extends JModelList{
public function __construct($config = array())
{
if (empty($config['filter_fields']))
{
$config['filter_fields'] = array(
'id', 'a.id',
'fullname', 'a.fullname',
);
$assoc = JLanguageAssociations::isEnabled();
if ($assoc)
{
$config['filter_fields'][] = 'association';
}
}
parent::__construct($config);
}
public function getListQuery()
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__ss_structure_tmp');
$search = $this->getState('filter.search');
$limit = $this->getState('filter.limit');
if (!empty($search)) {
$query->where('fullname LIKE "%' . $search .'%" ' );
}
if (!empty($limit)) {
$query->setLimit($limit);
}
return $query;
}
protected function populateState($ordering = 'a.fullname', $direction = 'asc')
{
$app = JFactory::getApplication();
if ($layout = $app->input->get('layout'))
{
$this->context .= '.' . $layout;
}
$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
$this->setState('filter.search', $search);
parent::populateState();
}
}
You need to provide the model to your controller using the getModel() method. Look in the articles controller of the com_content for example.
You need to add a table file with the publish function within:
defined('_JEXEC') or die;
use Joomla\Utilities\ArrayHelper;
class labTableStructurelist extends JTable
{
/**
* Constructor
*
* #param JDatabase &$db A database connector object
*/
public function __construct(&$db)
{
parent::__construct('#__ss_structure_tmp', 'id', $db);
}
/**
* Overloaded bind function to pre-process the params.
*
* #param array $array Named array
* #param mixed $ignore Optional array or list of parameters to ignore
*
* #return null|string null is operation was satisfactory, otherwise returns an error
*
* #see JTable:bind
* #since 1.5
*/
public function bind($array, $ignore = '')
{
$input = JFactory::getApplication()->input;
$task = $input->getString('task', '');
if (($task == 'save' || $task == 'apply') && (!JFactory::getUser()->authorise('core.edit.state', 'com_lab.structurelist.'.$array['id']) && $array['state'] == 1))
{
$array['state'] = 0;
}
if ($array['id'] == 0)
{
$array['created_by'] = JFactory::getUser()->id;
}
if (isset($array['params']) && is_array($array['params']))
{
$registry = new JRegistry;
$registry->loadArray($array['params']);
$array['params'] = (string) $registry;
}
if (isset($array['metadata']) && is_array($array['metadata']))
{
$registry = new JRegistry;
$registry->loadArray($array['metadata']);
$array['metadata'] = (string) $registry;
}
if (!JFactory::getUser()->authorise('core.admin', 'com_lab.structurelist.' . $array['id']))
{
$actions = JAccess::getActionsFromFile(
JPATH_ADMINISTRATOR . '/components/com_lab/access.xml',
"/access/section[#name='user']/"
);
$default_actions = JAccess::getAssetRules('com_lab.structurelist.' . $array['id'])->getData();
$array_jaccess = array();
foreach ($actions as $action)
{
$array_jaccess[$action->name] = $default_actions[$action->name];
}
$array['rules'] = $this->JAccessRulestoArray($array_jaccess);
}
// Bind the rules for ACL where supported.
if (isset($array['rules']) && is_array($array['rules']))
{
$this->setRules($array['rules']);
}
return parent::bind($array, $ignore);
}
/**
* This function convert an array of JAccessRule objects into an rules array.
*
* #param array $jaccessrules An array of JAccessRule objects.
*
* #return array
*/
private function JAccessRulestoArray($jaccessrules)
{
$rules = array();
foreach ($jaccessrules as $action => $jaccess)
{
$actions = array();
foreach ($jaccess->getData() as $group => $allow)
{
$actions[$group] = ((bool) $allow);
}
$rules[$action] = $actions;
}
return $rules;
}
/**
* Overloaded check function
*
* #return bool
*/
public function check()
{
// If there is an ordering column and this is a new row then get the next ordering value
if (property_exists($this, 'ordering') && $this->id == 0)
{
$this->ordering = self::getNextOrder();
}
return parent::check();
}
/**
* Method to set the publishing state for a row or list of rows in the database
* table. The method respects checked out rows by other users and will attempt
* to checkin rows that it can after adjustments are made.
*
* #param mixed $pks An optional array of primary key values to update. If not
* set the instance property value is used.
* #param integer $state The publishing state. eg. [0 = unpublished, 1 = published]
* #param integer $userId The user id of the user performing the operation.
*
* #return boolean True on success.
*
* #since 1.0.4
*
* #throws Exception
*/
public function publish($pks = null, $state = 1, $userId = 0)
{
// Initialise variables.
$k = $this->_tbl_key;
// Sanitize input.
ArrayHelper::toInteger($pks);
$userId = (int) $userId;
$state = (int) $state;
// If there are no primary keys set check to see if the instance key is set.
if (empty($pks))
{
if ($this->$k)
{
$pks = array($this->$k);
}
// Nothing to set publishing state on, return false.
else
{
throw new Exception(500, JText::_('JLIB_DATABASE_ERROR_NO_ROWS_SELECTED'));
}
}
// Build the WHERE clause for the primary keys.
$where = $k . '=' . implode(' OR ' . $k . '=', $pks);
// Determine if there is checkin support for the table.
if (!property_exists($this, 'checked_out') || !property_exists($this, 'checked_out_time'))
{
$checkin = '';
}
else
{
$checkin = ' AND (checked_out = 0 OR checked_out = ' . (int) $userId . ')';
}
// Update the publishing state for rows with the given primary keys.
$this->_db->setQuery(
'UPDATE `' . $this->_tbl . '`' .
' SET `state` = ' . (int) $state .
' WHERE (' . $where . ')' .
$checkin
);
$this->_db->execute();
// If checkin is supported and all rows were adjusted, check them in.
if ($checkin && (count($pks) == $this->_db->getAffectedRows()))
{
// Checkin each row.
foreach ($pks as $pk)
{
$this->checkin($pk);
}
}
// If the JTable instance value is in the list of primary keys that were set, set the instance.
if (in_array($this->$k, $pks))
{
$this->state = $state;
}
return true;
}
/**
* Define a namespaced asset name for inclusion in the #__assets table
*
* #return string The asset name
*
* #see JTable::_getAssetName
*/
protected function _getAssetName()
{
$k = $this->_tbl_key;
return 'com_lab.structurelist.' . (int) $this->$k;
}
/**
* Returns the parent asset's id. If you have a tree structure, retrieve the parent's id using the external key field
*
* #param JTable $table Table name
* #param integer $id Id
*
* #see JTable::_getAssetParentId
*
* #return mixed The id on success, false on failure.
*/
protected function _getAssetParentId(JTable $table = null, $id = null)
{
// We will retrieve the parent-asset from the Asset-table
$assetParent = JTable::getInstance('Asset');
// Default: if no asset-parent can be found we take the global asset
$assetParentId = $assetParent->getRootId();
// The item has the component as asset-parent
$assetParent->loadByName('com_lab');
// Return the found asset-parent-id
if ($assetParent->id)
{
$assetParentId = $assetParent->id;
}
return $assetParentId;
}
/**
* Delete a record by id
*
* #param mixed $pk Primary key value to delete. Optional
*
* #return bool
*/
public function delete($pk = null)
{
$this->load($pk);
$result = parent::delete($pk);
return $result;
}
}
Please note, that this is just an example of a table file, I can't guarantee that this would work just by copy&paste. Please check com_content/table for another example.
Also add a getTable() to your List single item model:
public function getTable($type = 'view_name', $prefix = 'labTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
Please check if file structure is correct:
List View
structurelist**s** -> list view with multiple items
|-> controller/structurelists.php
|-> models/structurelists.php
|-> view/structurelists/
Single View / List View (publish() for example)
structurelist -> single item view (edit view)
|-> models/structurelist.php (this is important for the publish() in the list view)
|-> models/forms/structurelist.xml
|-> tables/structurelist.php (this is important for the publish() in the list view)
|-> view/structurelist/
Feel free to comment if you need more help.
I try to get value of a private variable (limit), but I get the following error:
Fatal error: Uncaught Error: Using $this when not in object context in /home/vagrant/Code/wp/wp-content/plugins/StorePress/app/library/Pagination.php on line 36
My Class:
class Pagination
{
private $limit = 0;
private $limit_start = 0;
private $total = 0;
/**
* Generate Pagination for Products
* #param $pagination
* #return string
*/
public function __constructor($pagination = null)
{
$this->limit = $pagination['limit'];
$this->lim_start = ($pagination['start']) ?: null;
$this->total = $pagination['total'];
}
public function generatePagination()
{
echo $this->limit;
}
Here, I'm trying to print "$this->limit", a private variable, but it's not allowed to print the value that are assigned by the "__constructor".
Is there anything wrong in my code or is there any other solution to get that value?
I think, that the problem is in your OOP construction. You cannot echo $this private variable, when you don't create class object as first. So the solution might be:
class Pagination
{
private $limit = 0;
private $limit_start = 0;
private $total = 0;
/**
* Generate Pagination for Products
* #param $pagination
* #return string
*/
public function __constructor($pagination = null)
{
$this->limit = $pagination['limit'];
$this->lim_start = ($pagination['start']) ?: null;
$this->total = $pagination['total'];
}
public function generatePagination()
{
return $this->limit;
}
and then in your code, where you need to echo the limit value, you can use:
$pagination = new Pagination();
echo $pagination->generatePagination();
At first line, you will create new Pagination() object and in the second line, you will return the $limit value from your generatePagination class function.
Shouldn't your keyword __constructor be __construct instead according to this link
I've recently learned about the advantages of using Dependency Injection (DI) in my PHP application.
However, I'm still unsure how to create my container for the dependencies. Before, I use a container from a framework and I want to understand how is he doing things in back and reproduce it.
For example:
The container from Zend 2. I understand that the container make class dynamic, he does not have to know about them from the beginning, he checks if he already has that class in his registry and if he has not he check if that class exist and what parameters has inside constructor and put it in his own registry so next time could take it from there, practical is doing everything dynamic and it is completing his own registry, so we do not have to take care of nothing once we implement the container as he can give as any class we want even if we just make that class.
Also if I want to getInstance for A which needs B and B needs C I understand that he doing this recursive and he goes and instantiate C then B and finally A.
So I understand the big picture and what is he suppose to do but I am not so sure about how to implement it.
You may be better off using one of the existing Dependency Containers out there, such as PHP-DI or Pimple. However, if you are looking for a simpler solution, then I've implemented a Dependency Container as part of an article that I wrote here: http://software-architecture-php.blogspot.com/
Here is the code for the container
class Container implements \DecoupledApp\Interfaces\Container\ContainerInterface
{
/**
* This function resolves the constructor arguments and creates an object
* #param string $dataType
* #return mixed An object
*/
private function createObject($dataType)
{
if(!class_exists($dataType)) {
throw new \Exception("$dataType class does not exist");
}
$reflectionClass = new \ReflectionClass($dataType);
$constructor = $reflectionClass->getConstructor();
$args = null;
$obj = null;
if($constructor !== null)
{
$block = new \phpDocumentor\Reflection\DocBlock($constructor);
$tags = $block->getTagsByName("param");
if(count($tags) > 0)
{
$args = array();
}
foreach($tags as $tag)
{
//resolve constructor parameters
$args[] = $this->resolve($tag->getType());
}
}
if($args !== null)
{
$obj = $reflectionClass->newInstanceArgs($args);
}
else
{
$obj = $reflectionClass->newInstanceArgs();
}
return $obj;
}
/**
* Resolves the properities that have a type that is registered with the Container.
* #param mixed $obj
*/
private function resolveProperties(&$obj)
{
$reflectionClass = new \ReflectionClass(get_class($obj));
$props = $reflectionClass->getProperties();
foreach($props as $prop)
{
$block = new \phpDocumentor\Reflection\DocBlock($prop);
//This assumes that there is only one "var" tag.
//If there are more than one, then only the first one will be considered.
$tags = $block->getTagsByName("var");
if(isset($tags[0]))
{
$value = $this->resolve($tags[0]->getType());
if($value !== null)
{
if($prop->isPublic()) {
$prop->setValue($obj, $value);
} else {
$setter = "set".ucfirst($prop->name);
if($reflectionClass->hasMethod($setter)) {
$rmeth = $reflectionClass->getMethod($setter);
if($rmeth->isPublic()){
$rmeth->invoke($obj, $value);
}
}
}
}
}
}
}
/**
*
* #param string $dataType
* #return object|NULL If the $dataType is registered, the this function creates the corresponding object and returns it;
* otherwise, this function returns null
*/
public function resolve($dataType)
{
$dataType = trim($dataType, "\\");
$obj = null;
if(isset($this->singletonRegistry[$dataType]))
{
//TODO: check if the class exists
$className = $this->singletonRegistry[$dataType];
$obj = $className::getInstance();
}
else if(isset($this->closureRegistry[$dataType]))
{
$obj = $this->closureRegistry[$dataType]();
}
else if(isset($this->typeRegistry[$dataType]))
{
$obj = $this->createObject($this->typeRegistry[$dataType]);
}
if($obj !== null)
{
//Now we need to resolve the object properties
$this->resolveProperties($obj);
}
return $obj;
}
/**
* #see \DecoupledApp\Interfaces\Container\ContainerInterface::make()
*/
public function make($dataType)
{
$obj = $this->createObject($dataType);
$this->resolveProperties($obj);
return $obj;
}
/**
*
* #param Array $singletonRegistry
* #param Array $typeRegistry
* #param Array $closureRegistry
*/
public function __construct($singletonRegistry, $typeRegistry, $closureRegistry)
{
$this->singletonRegistry = $singletonRegistry;
$this->typeRegistry = $typeRegistry;
$this->closureRegistry = $closureRegistry;
}
/**
* An array that stores the mappings of an interface to a concrete singleton class.
* The key/value pair corresond to the interface name/class name pair.
* The interface and class names are all fully qualified (i.e., include the namespaces).
* #var Array
*/
private $singletonRegistry;
/**
* An array that stores the mappings of an interface to a concrete class.
* The key/value pair corresond to the interface name/class name pair.
* The interface and class names are all fully qualified (i.e., include the namespaces).
* #var Array
*/
private $typeRegistry;
/**
* An array that stores the mappings of an interface to a closure that is used to create and return the concrete object.
* The key/value pair corresond to the interface name/class name pair.
* The interface and class names are all fully qualified (i.e., include the namespaces).
* #var Array
*/
private $closureRegistry;
}
The above code can be found here: https://github.com/abdulla16/decoupled-app (under the /Container folder)
You can register your dependencies as a singleton, as a type (every time a new object will be instantiated), or as a closure (the container will call the function that you register and that function is expected to return the instance).
For example,
$singletonRegistry = array();
$singletonRegistry["DecoupledApp\\Interfaces\\UnitOfWork\\UnitOfWorkInterface"] =
"\\DecoupledApp\\UnitOfWork\\UnitOfWork";
$typeRegistry = array();
$typeRegistry["DecoupledApp\\Interfaces\\DataModel\\Entities\\UserInterface"] =
"\\DecoupledApp\\DataModel\\Entities\\User";
$closureRegistry = array();
$closureRegistry["DecoupledApp\\Interfaces\\DataModel\\Repositories\\UserRepositoryInterface"] =
function() {
global $entityManager;
return $entityManager->getRepository("\\DecoupledApp\\DataModel\\Entities\\User");
};
$container = new \DecoupledApp\Container\Container($singletonRegistry, $typeRegistry, $closureRegistry);
This Container resolves properties of a class as well as the constructor parameters.
I have done a very simple IoC class which works as intended. I've investigated the IoC and DI pattern and especially after reading this answer. Let me know if something is not right or you have any questions .
<?php
class Dependency {
protected $object = null;
protected $blueprint = null;
/**
* #param $instance callable The callable passed to the IoC object.
*/
public function __construct($instance) {
if (!is_object($instance)) {
throw new InvalidArgumentException("Received argument should be object.");
}
$this->blueprint = $instance;
}
/**
* (Magic function)
*
* This function serves as man-in-the-middle for method calls,
* the if statement there serves for lazy loading the objects
* (They get created whenever you call the first method and
* all later calls use the same instance).
*
* This could allow laziest possible object definitions, like
* adding annotation parsing functionality which can extract everything during
* the call to the method. once the object is created it can get the annotations
* for the method, automatically resolve its dependencies and satisfy them,
* if possible or throw an error.
*
* all arguments passed to the method get passed to the method
* of the actual code dependency.
*
* #param $name string The method name to invoke
* #param $args array The array of arguments which will be passed
* to the call of the method
*
* #return mixed the result of the called method.
*/
public function __call($name, $args = array())
{
if (is_null($this->object)) {
$this->object = call_user_func($this->blueprint);
}
return call_user_func_array(array($this->object, $name), $args);
}
}
/*
* If the object implements \ArrayAccess you could
* have easier access to the dependencies.
*
*/
class IoC {
protected $immutable = array(); // Holds aliases for write-protected definitions
protected $container = array(); // Holds all the definitions
/**
* #param $alias string Alias to access the definition
* #param $callback callable The calback which constructs the dependency
* #param $immutable boolean Can the definition be overriden?
*/
public function register ($alias, $callback, $immutable = false) {
if (in_array($alias, $this->immutable)) {
return false;
}
if ($immutable) {
$this->immutable[] = $alias;
}
$this->container[$alias] = new Dependency($callback);
return $this;
}
public function get ($alias) {
if (!array_key_exists($alias, $this->container)) {
return null;
}
return $this->container[$alias];
}
}
class FooBar {
public function say()
{
return 'I say: ';
}
public function hello()
{
return 'Hello';
}
public function world()
{
return ', World!';
}
}
class Baz {
protected $argument;
public function __construct($argument)
{
$this->argument = $argument;
}
public function working()
{
return $this->argument->say() . 'Yep!';
}
}
/**
* Define dependencies
*/
$dic = new IoC;
$dic->register('greeter', function () {
return new FooBar();
});
$dic->register('status', function () use ($dic) {
return new Baz($dic->get('greeter'));
});
/**
* Real Usage
*/
$greeter = $dic->get('greeter');
print $greeter->say() . ' ' . $greeter->hello() . ' ' . $greeter->world() . PHP_EOL . '<br />';
$status = $dic->get('status');
print $status->working();
?>
I think the code is pretty self-explanatory, but let me know if something is not clear
Because I haven't find anything near what I wanted,I tried to implement on my own a container and I want to hear some opinion about how is looking,because I've start to learn php and oop a month ago a feedback is very important for me because I know I have many things to learn,so please feel free to bully my code :))
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<?php
class ioc
{
private $defs;
static $instance;
private $reflection;
private function __construct()
{
$defs = array();
$reflection = array();
}
private function __clone()
{
;
}
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new ioc();
}
return self::$instance;
}
public function getInstanceOf($class)
{
if (is_array($this->defs) && key_exists($class, $this->defs)) {
if (is_object($this->defs[$class])) {
return $this->defs[$class];
}
} else {
if (class_exists($class)) {
if (is_array($this->reflection) && key_exists($class, $this->reflection)) {
$reflection = $this->reflection[$class];
} else {
$reflection = new ReflectionClass($class);
$this->reflection[$class] = $reflection;
}
$constructor = $reflection->getConstructor();
if ($constructor) {
$params = $constructor->getParameters();
if ($params) {
foreach ($params as $param) {
$obj[] = $this->getInstanceOf($param->getName());
}
$class_instance = $reflection->newInstanceArgs($obj);
$this->register($class, $class_instance);
return $class_instance;
}
}
if (!$constructor || !$params) {
$class_instance = new $class;
$this->register($class, $class_instance);
return $class_instance;
}
}
}
}
public function register($key, $class)
{
$this->defs[$key] = $class;
}
}
?>
I'm trying to use a foreach loop for an array of objects. Inside of the BeginBattle() method I want to iterate through all of the objects and increment their played count automatically. Unfortunately, the web browser shows I have an error: Fatal error: Call to a member function BattleInitiated() on a non-object in /nfs/c05/h01/mnt/70299/domains/munchkinparty.neededspace.net/html/Battle.php on line 75
Any ideas?
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of Battle
*
* #author joshualowry
*/
class Battle {
/**
*
* #var <type>
*/
private $_players;
/**
*
* #var <type>
*/
private $_battleInProgress;
/**
*
*/
public function Battle(){
$this->_players = array();
$this->_battleInProgress = FALSE;
}
/**
*
* #param <type> $player
* #return <type>
*/
public function AddPlayer($player){
if(!$this->_battleInProgress)
$this->_players[] = $player;
else
return;
//Spit some error
}
/**
*
* #param <type> $player
* #return <type>
*/
public function BattleWon($player){
if($player != NULL)
$player->BattleWon();
else
return;
//Spit some error
}
/** GetPlayerByName Get the player's object by the player's name field.
*
* #param <type> $playerName
* #return <type>
*/
public function GetPlayerByName($playerName){
foreach($this->_players as &$player) {
if($player->GetName() == $playerName)
return $player;
}
return NULL;
}
/**
*
*/
public function BeginBattle(){
$this->_battleInProgress = TRUE;
foreach($this->_players as $player){
$player->BattleInitiated();
}
}
/**
*
*/
public function DisplayCurrentBoard() {
echo "Name Alias Wins Battles<br/>";
foreach($this->_players as &$player){
echo "$player->GetName() $player->GetAlias() $player->GetWins() $player->GetBattles()<br/>";
}
}
}
?>
This is where everything is declared and called:
<?php
include 'Battle.php';
include 'Person.php';
include 'Player.php';
$currentBattle = new Battle();
$playerA = new Player("JohnnyDanger","John",0,0);
$playerB = new Player("JoshTheJest","Josh",0,0);
$PlayerC = new Player("CarbQueen","Nicole",0,0);
$currentBattle->AddPlayer($playerA);
$currentBattle->AddPlayer($playerB);
$currentBattle->AddPlayer($playerC);
$currentBattle->BeginBattle();
$currentBattle->BattleWon($currentBattle->GetPlayerByName("Josh"));
$currentBattle->DisplayCurrentBoard();
?>
The Player Class
<?php
/**
* Description of Player
*
* #author joshualowry
*/
class Player extends Person {
private $_alias;
private $_wins;
private $_battles;
public function Player($name, $alias, $wins, $battles) {
parent::SetName($name);
$this->_alias = $alias;
$this->_battles = $battles;
if($battles == 0) {
$this->_wins = 0;
}
else {
$this->_wins = $wins;
}
}
protected function SetAlias($value){
$this->_alias = $value;
}
public function GetAlias(){
return $this->_alias;
}
protected function SetBattles($value) {
$this->_battles = $value;
}
public function GetBattles(){
return $this->_battles;
}
protected function SetWins($value) {
$this->_wins = $value;
}
public function GetWins() {
return $this->_wins;
}
public function BattleWon(){
$this->_wins += 1;
}
public function BattleInitiated(){
$this->_battles += 1;
}
}
?>
The error message indicates that you are trying to all the BattleInitiated() method on something that wasn't an object.
Judging from your code, the problem seems to be with this loop, in the BeginBattle() method :
foreach($this->_players as $player){
$player->BattleInitiated();
}
Which means $player, at least one in your array, is probably not an object ; maybe it's null, or an array ?
To know more, you should use var_dump to display the content of $this->_players before the loop, just to make sure it contains what you expect it to :
public function BeginBattle(){
var_dump($this->_players);
$this->_battleInProgress = TRUE;
foreach($this->_players as $player){
$player->BattleInitiated();
}
}
If $this->_players doesn't contain what you expect it to (and it probably doesn't !), you'll then have to find out why...
Considering $this->_players is modified by the AddPlayer() method, which adds what it receives to the end of the array, I would bet that AddPlayer() is called at least once without a correct $player as a parameter.
To help with that, you could use var_dump on the $player being added :
public function AddPlayer($player){
var_dump($player);
if(!$this->_battleInProgress)
$this->_players[] = $player;
else
return;
//Spit some error
}
If that var_dump indicates at least once that $player is not an object (for instance, it's null, or an array, or a string, ...), that's the cause of your Fatal Error.
don't you see it??
it's all because of a small typo:
$playerA = new Player("JohnnyDanger","John",0,0);
$playerB = new Player("JoshTheJest","Josh",0,0);
$PlayerC = new Player("CarbQueen","Nicole",0,0);
$currentBattle->AddPlayer($playerA);
$currentBattle->AddPlayer($playerB);
$currentBattle->AddPlayer($playerC);
declared: $_P_layerC
used: $_p_layerC
correct that and you're good to go
Your $player variable is either null or not an Object of the type you want it to be.
PlayerObject is what ever your class name for player is.
For example
$battle=new Battle();
$player1=new PlayerObject();
$player2="player";
$battle->AddPlayer($player1);
$battle->AddPlayer($player2);
$battle->BeginBattle();
when you call BeginBattle() the $player1->BattleInitiated(); will be successful but the $player2->BattleInitiated() will give you the fatal error and stop your code from running. same if $player2 was null, an integer or something that is not PlayerObject.