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.
Related
i am trying web scraping so i get this error on "\vendor\symfony\dom-crawler\Crawler.php:552"
here is the crawler.php code what the browser showed me:
#throws \InvalidArgumentException When current node is empty
*/
public function text(string $default = null, bool $normalizeWhitespace = true): string
{
if (!$this->nodes) {
if (null !== $default) {
return $default;
}
throw new \InvalidArgumentException('The current node list is empty.');
}
$text = $this->getNode(0)->nodeValue;
if ($normalizeWhitespace) {
return trim(preg_replace('/(?:\s{2,}+|[^\S ])/', ' ', $text));
}
return $text;
}
This exception is thrown when trying to access the text of an empty node list. I have written a util class for this purpose, as I don't always mind the value being empty. Simply pass the node list you want to get the inner text from, like so CrawlUtil::innerText($nodeList). Hope it will help somebody in the future :)
use Symfony\Component\DomCrawler\Crawler;
class CrawlUtil
{
/**
* Suppresses exception that node list is empty.
*
* #param Crawler $crawler
*
* #return string|null
*/
public static function innerText(Crawler $crawler): ?string
{
if ($crawler->count() > 0 && $crawler->text() !== '') {
return $crawler->innerText();
}
return null;
}
}
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);
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 can't add new type with zend framework. I've tried this
$server = new Zend_Soap_Server('http://localhost/CycleProphet/amember/ws/index/wsdl');
$server->addComplexType('AMemberUser');
class AMemberUser
{
public $UserId;
public $FirstName;
public $LastName;
}
Type has been added, but it is empty. I use this article http://framework.zend.com/manual/en/zend.soap.wsdl.html#zend.soap.wsdl.types.add_complex, but it isn't help me.
After your comment I decided to rewrite my answer and provide you some solution with wsdl:
<?php
require_once('Zend/Soap/Client.php');
require_once('Zend/Soap/Server.php');
require_once('Zend/Soap/Wsdl.php');
require_once('Zend/Soap/AutoDiscover.php');
class SoapController extends AppController
{
public function zendclientAction()
{
$_client = new Zend_Soap_Client('http://localhost/php5_testapp/soap/zendserver?wsdl');
$_ret = $_client->addNumbers(3, 5);
echo('<pre>');
var_dump($_ret);
echo('<pre>');
die();
}
public function zendserverAction()
{
if(isset($_GET['wsdl'])) {
$_autod = new Zend_Soap_AutoDiscover();
$_autod->setClass('MySoapServerClass');
$_autod->handle();
}
else {
$_server = new Zend_Soap_Server('http://localhost/php5_testapp/soap/zendserver?wsdl');
$_server->setClass("MySoapServerClass");
$_server->handle();
}
exit;
}
}
/**
* My Soap Server Class
*/
class MySoapServerClass {
/**
* This method adds two numbers
*
* #param integer $a
* #param integer $b
* #return string
*/
public function addNumbers($a, $b) {
return 'Outcome is: ' . ($a + $b);
}
}
Now you can add whatever class you want! But remember - your class should be well documented, because WSDL file is generated basing on this.
Hope it helps!
I am writing my own administration and, off course I am using Smarty.
Now, what I would like to do is to add a access check function much similar to the {if} tag.
What I would like to write is:
{userAccess module='MyModule' action='WriteMessage'}
Yeey.. I can write something. My name is {$myName}.
{/userAccess}
but I can't figure out how to. Can someone please point me into the right direction?
Also, if possible adding and {else} to it. So the code would be:
{userAccess module='MyModule' action='WriteMessage'}
Yeey.. I can write something. My name is {$myName}.
{else}
Nooo.. :( I don't have access.
{/userAccess}
I solved it creating my own "internal" function for smarty. This might not be the way Smarty intended it to be used, but it sure works for me... which is the most important thing for me.
This is my end result:
<?php
/**
* Smarty Internal Plugin Compile UserAccess
*
* Compiles the {useraccess} {useraccesselse} {/useraccess} tags
*
* #package Smarty
* #subpackage Compiler
* #author Paul Peelen
*/
/**
* Smarty Internal Plugin Compile useraccess Class
*/
class Smarty_Internal_Compile_useraccess extends Smarty_Internal_CompileBase {
// attribute definitions
public $required_attributes = array('module', 'action');
public $optional_attributes = array('userid'); // Not yet implemented
public $shorttag_order = array('module','action','userid');
/**
* Compiles code for the {useraccess} tag
*
* #param array $args array with attributes module parser
* #param object $compiler compiler object
* #param array $parameter array with compilation parameter
* #return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
$tpl = $compiler->template;
// check and get attributes
$_attr = $this->_get_attributes($args);
$module = $_attr['module'];
$action = $_attr['action'];
if (!is_string($module) || !is_string($action))
{
exit ("ERROR");
}
$this->_open_tag('useraccess', array('useraccess', $this->compiler->nocache, $module, $action));
$this->compiler->nocache = $this->compiler->nocache | $this->compiler->tag_nocache;
$output = "<?php ";
$output .= "\$oAuth = \$GLOBALS['oAuth'];\n";
$output .= " \$_smarty_tpl->tpl_vars[$module] = new Smarty_Variable;\n";
$compiler->local_var[$module] = true;
$output .= " \$_smarty_tpl->tpl_vars[$action] = new Smarty_Variable;\n";
$compiler->local_var[$action] = true;
$output .= "if (\$oAuth->getUserSubRights($action,$module)) {";
$output .= "?>";
return $output;
}
}
/**
* Smarty Internal Plugin Compile UserAccessElse Class
*/
class Smarty_Internal_Compile_UserAccessElse extends Smarty_Internal_CompileBase {
/**
* Compiles code for the {useraccesselse} tag
*
* #param array $args array with attributes module parser
* #param object $compiler compiler object
* #param array $parameter array with compilation parameter
* #return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
// check and get attributes
$_attr = $this->_get_attributes($args);
list($_open_tag, $nocache, $item, $key) = $this->_close_tag(array('useraccess'));
$this->_open_tag('useraccesselse', array('useraccesselse', $nocache, $item, $key));
return "<?php } else { ?>";
}
}
/**
* Smarty Internal Plugin Compile UserAccessclose Class
*/
class Smarty_Internal_Compile_UserAccessclose extends Smarty_Internal_CompileBase {
/**
* Compiles code for the {/useraccess} tag
*
* #param array $args array with attributes module parser
* #param object $compiler compiler object
* #param array $parameter array with compilation parameter
* #return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
// check and get attributes
$_attr = $this->_get_attributes($args);
// must endblock be nocache?
if ($this->compiler->nocache) {
$this->compiler->tag_nocache = true;
}
list($_open_tag, $this->compiler->nocache, $item, $key) = $this->_close_tag(array('useraccess', 'useraccesselse'));
unset($compiler->local_var[$item]);
if ($key != null) {
unset($compiler->local_var[$key]);
}
return "<?php } ?>";
}
}
I hope this helps anybody who has this problem in the future.
You could try registerPlugin.
$smarty->registerPlugin("block","userAccess", array('YourClass', 'your_function'));
and your class:
class YourClass {
static function your_function($params, $content, $smarty, &$repeat, $template) {
$module = $params['module'];
$action = $params['action'];
if ($action == 'WriteMessage' && $user_may_write_message) {
return $content;
else
return '';
}
}
The problem here is that you are not so easiliy able to use variables inside this block. Maybe you can send the inner content to smarty again, but since it only allows template files in the function fetch() I'm not quite sure if this works.
What could help though is the smarty function eval, but I have not worked with it yet.