joomla component not calling any model function and controller function - php

I am sending a ajax request in function and calling model function but model function not calling and i also try a local controller function but not call any local function
controller
<?php
defined('_JEXEC') or die;
jimport('joomla.application.component.controller');
class IgalleryController extends JControllerLegacy
{
function __construct($config = array())
{
$config['base_path'] = JPATH_SITE.'/components/com_igallery';
parent::__construct($config);
}
function ajaxrequest()
{
//JModelLegacy::addIncludePath(JPATH_SITE . '/components/com_igallery/models', 'category');
//echo $db = JFactory::getDBO();
$model = $this->getModel('category');
$this->params = JComponentHelper::getParams('com_igallery');
$this->source = JRequest::getCmd('igsource', 'component');
//
$igid = JFactory::getApplication()->input->get('igid');
$Itemid = JFactory::getApplication()->input->get('Itemid');
$this->catid = JRequest::getInt('igid', 0);
$this->category = $model->getCategory($this->catid);
$profileId = JRequest::getInt('igpid', 0);
$profileId = $profileId == 0 ? $this->category->profile : $profileId;
$user = JFactory::getUser();
//print_r($user); die;
$this->profile = $model->getProfile($profileId);
$searchChildren = JRequest::getInt('igchild', 0);
$tags = JRequest::getVar('igtags', '');
//
$limit = JRequest::getInt('iglimit', 0);
$limit = $limit == 0 ? 1000 : $limit;
$foo = $this->foo();
print_r($foo);
$this->photoList = $model->getCategoryImagesList($this->profile, $this->catid, $tags, $searchChildren, $limit);
//
print_r($this->photoList);
}
function $this->foo()
{
return true;
}
...
in above code also print $foo variable but not get true or 1 value;

You must override function getModel() in your controller
parent model has construct:
public function getModel($name = '', $prefix = '', $config = array('ignore_request' => true))
You lacked $prefix and you also add include path of the model file if necessary
Regarding issue return value true of false, you must echo 1 for true of 0 for false and stop the process by die function. The return method will show so much html of joomla page.
function $this->foo()
{
echo 1;
die;
}

Related

Laravel, Call function from class returns null value

How to get values from the function below if I want to put it in a class? acutally if I called it directly from controller it works fine but when I called it from class it returns null value please help me
Simply I need to add this in the screen function in a class so no need to repeat the code inside the controller many times, please note that in the controller function it works fine but in class it returns null value
Class:
public function getStoresDistance($allstores)
{
$stores = collect([]);
foreach (session('storeinfo') as $storeInfo) {
$store = $allstores->find($storeInfo['id']);
if ($store) {
$store->distance = $storeInfo['distance'];
$stores[] = $store;
if (!Collection::hasMacro('paginate')) {
Collection::macro('paginate', function ($perPage = 25, $page = null, $options = []) {
$options['path'] = $options['path'] ?? request()->path();
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
return new LengthAwarePaginator(
$this->forPage($page, $perPage)->values(),
$this->count(),
$perPage,
$page,
$options
);
});
}
}
}
}
call from controller:
$allstores = Storeinfo::where('show', 'y')->get();
$findstores = Helper::getStoresDistance($allstores);
You need 'return' on function that you want to call (return what data to send/call)
just type 'Class::function' inside your class
like this
class ExampleController extends Controller
{
public function yourController()
{
$allstores = Storeinfo::where('show', 'y')->get();
$findstores = ExampleController::getStoresDistance($allstores);
return $findstores;
}
public function getStoresDistance($allstores)
{
$stores = collect([]);
return session('storeinfo');
foreach (session('storeinfo') as $storeInfo) {
$store = $allstores->find($storeInfo['id']);
if ($store) {
$store->distance = $storeInfo['distance'];
$stores[] = $store;
if (!Collection::hasMacro('paginate')) {
Collection::macro('paginate', function ($perPage = 25, $page = null, $options = []) {
$options['path'] = $options['path'] ?? request()->path();
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
return new LengthAwarePaginator(
$this->forPage($page, $perPage)->values(),
$this->count(),
$perPage,
$page,
$options
);
});
}
}
}
}
}
If the function is common for multiple controllers, move it to a PHP trait. Traits are specifically designed for reusability purpose. You can then use that trait in your controller and call its function as you would your controller functions like so $this->yourFunction(). Below is how your code will look:
Trait:
trait StoresDistance
{
public function storesDistance(){}
}
Controller:
class YourController extends Controller
{
use StoresDistance;
public function getStoresDistance($allstores)
{
// some code
$this->storesDistance();
// some code
}
}
Reference Docs: https://www.php.net/manual/en/language.oop5.traits.php

Use session in static method (cakephp 4 and 3.6+)

If I try this is a class with static methods:
public static function chkLog($role)
{
$userrole = $this->getRequest()->getSession()->read('userrole');
return $userrole;
/// more code
Even tried:
public static function chkLog($role)
{
$userrole = Session::read('userrole');
return $userrole;
/// more code
In laravel I can:
public static function userRole($role = null)
{
$userrole = Auth::user()->role;
$checkrole = explode(',', $userrole);
if (in_array($role, $checkrole)) {
return $role;
}
return false;
}
usage
public function scopegetPets($query, $petsearch = '')
{
$petsearch = $petsearch . "%";
$query = Pet::where('petname', 'like', $petsearch);
if (ChkAuth::userRole('admin') === false) {
$userid = Auth::user()->id;
$query->where('ownerid', '=', $userid);
}
$results = $query->orderBy('petname', 'asc')->paginate(5);
return $results;
}
But in cakephp to call statically I had to write this:
public static function __callStatic($method, $params)
{
$instance = ChkAuth::class;
$c = new $instance;
return $c->$method(...array_values($params));
}
In order to call this:
public function userRole($role = null)
{
$userrole = $this->getRequest()->getSession()->read('userrole');
$checkrole = explode(',', $userrole);
if (in_array($role, $checkrole)) {
return $role;
}
return false;
// more
And usage:
public function getPets($offset = "", $rowsperpage = "", $petsearch = "")
{
$pagingQuery = "LIMIT {$offset}, {$rowsperpage}";
$petsearch = $petsearch . "%";
if (Auth::chkRole('admin') === true) {
return DB::select("SELECT * FROM " . PREFIX . "pets " . $pagingQuery);
}
$authid = Auth::authId();
return DB::select("SELECT * FROM " . PREFIX . "pets WHERE ownerid = :authid " . $pagingQuery, ["authid" => $authid]);
}
So basically I am trying to figure out how to use session in cake php inside a static method.
Note the __callStatic works, but as a work a round.
CakePHP's Router class includes a static function to return the request object. The request object includes a function to return the session. So:
Router::getRequest()->session()
or, as of version 3.5:
Router::getRequest()->getSession()

Use variable from "public static function" in another "public static function"

I know this question is asked like a hundred times in hundred different ways. But I just can't get this particular one to work. I am really confused.
This is the very beginning of my script:
<?php
class API {
protected static $message, $data, $status, $session, $token, $dbo, $app;
const FAIL = 0;
const SUCCESS = 1;
const INCOMPLETE_ARGS = 2;
const GROUP_ALLOW = array(5);
public static function Init() {
global $app;
self::$status = false;
self::$message = "Invalid request.";
self::$data = "";
}
public static function Render() {
echo preg_replace("/\\\\u([0-9abcdef]{4})/", "&#x$1;", json_encode(array(
"status" => self::$status,
"message" => self::$message,
"data" => self::$data))
);
}
Then there is this function:
public static function Login() {
$email = (isset($_REQUEST['email'])) ? $_REQUEST['email'] : "";
$password = (isset($_REQUEST['password'])) ? $_REQUEST['password'] : "";
require_once ("../app/Mage.php");
umask(0);
ob_start();
session_start();
Mage::app('default');
Mage::getSingleton("core/session", array("name" => "frontend"));
$b2bwebsiteid = Mage::getStoreConfig('base/general/b2bwebsite');
//$websiteId = Mage::app()->getWebsite()->getId();
//$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $b2bwebsiteid;
$customer->loadByEmail($email);
$countryCodeBE = $customer->getDefaultBillingAddress()->getCountry();
$countrybe = Mage::getModel('directory/country')->loadByCode($countryCodeBE);
$countryid = $countrybe->getCountryId();
.....
.....
And in between there is a lot more code and functions.
Now a bit further, there is another function:
public static function ProductInfoNew() {
And now the thing I want, is to load the variable $countryid from that first function in the ProductInfoNew function so that I can do something like this:
if ($countryid == "BE") {
$groupid = 6;
}
else {
$groupid = 4;
}
But the output always seems to be NULL or Empty.
I tried setting the $countryid variable as global, static, tried to load the variable with self:: and I tried so many things but I can't get it to work.
Does anyone know the correct solution to do this?
Thanks a lot in advance.
$countryid should be a field inside of the class you are using.
class API {
private static $country_id;
public static function ProductInfoNew() {
if (self::$country_id == "BE") {
$groupid = 6;
} else {
$groupid = 4;
}
}
}

php function undefined when it is defined

I am having some problem with scope i assume, but i cannot for the life of me figure out what that problem is...
I keep getting a function undefined error for the following three functions whenever they are called; addUser, removeUser, updatePlayer. Anyone have any idea what's wrong? full code below (it is a pocketmine plugin):
<?php
/*
__PocketMine Plugin__
name=X
description=X
version=0.0.1
author=X
class=X
apiversion=10
*/
class X implements Plugin {
private $api;
public $continents = array();
public $allContinents = array("NA" => 0, "SA" => 0, "AF" => 0, "AS" => 0, "OC" => 0, "EU" => 0);
public function __construct(ServerAPI $api, $server = false){
$this->api = $api;
}
public function init(){
//Initialize the on player join event handler
$this->api->addHandler("player.spawn", array($this, "onPlayerJoin"));
$this->api->addHandler("player.quit", array($this, "onPlayerQuit"));
//Setup Config
$this->path = $this->api->plugin->configPath($this);
$this->msgs = new Config($this->path . "config.yml", CONFIG_YAML, array("AuthToken" => "", "Delay" => "5"));
$this->msgs = $this->api->plugin->readYAML($this->path . "config.yml");
}
// <--- updatePlayer --->
public function updatePlayer($user) {
}
// <--- Country Handler --->
public function addUser($user, $continents, $allContinents) {
$ip = $user->ip;
$username = $user->username;
$gi = geoip_open($this->path ."GeoIP.dat",GEOIP_STANDARD);
$continent = geoip_continent_code_by_name($gi, $ip);
array_push($continents, $username);
$continents[$username] = $continent;
$allContinents[$continent] += 1;
return $continents;
return $allContinents;
}
public function removeUser($user, $continents, $allContinents) {
$username = $user->username;
$continent = $continents[$username];
unset($continents[$username]);
$allContinents[$continent] -= 1;
return $continents;
return $allContinents;
}
// <--- Rquest Ad --->
public function requestAd() {
}
/*public function send() {
while(true) {
sleep(240);
}
}
}*/
//On player join event handler
public function onPlayerJoin($user){
$username = $user->username;
addUser($user);
updatePlayer($user);
//Check if plugin is setup
if ($this->api->ban->isOp($username) && $this->msgs["AuthToken"] == "") {
$this->api->chat->sendTo(false, "Please visit X to setup X.", $username);
}
}
public function onPlayerQuit($user){
removeUser($user);
}
public function __destruct(){
}
}
?>
If you're calling them from the same class or an extended class then you need to use $this.
public function onPlayerJoin($user){
$username = $user->username;
$this->addUser($user);
$this->updatePlayer($user);
}
Unless it's a static function, then you would use self::.
You need to instantiate an instance of class X, then call the functions as members of that object. For example:
$myX = new X();
$myX->addUser();
Cheers

Use Reflection class to pass exact number of parameters to class constructor PHP

I am creating my own MVC framework and the way I handle creation of models is as follows:
class ModelFactory {
public function __construct() {
parent::__construct();
}
public static function Create($model, $params = array()) {
if ( ! empty($model)) {
$model = ucfirst(strtolower($model));
$path = 'application/models/' . $model . '.php';
if (file_exists($path)) {
$path = rtrim(str_replace("/", "\\", $path), '.php');
$modelConstruct = new \ReflectionMethod($path, '__construct');
$numParams = $modelConstruct->getNumberOfParameters();
//fill up missing holes with null values
if (count($params) != $numParams) {
$tempArray = array_fill(0, $numParams, null);
$params = ($params + $tempArray);
}
//instead of thi
return new $path($params);
//I want to DO THIS
return new $path($param1, $param2, $param3 ... $paramN)
//where $paramN is the last value from $params array
}
}
return null;
}
}
a simple Model example:
class UsersModel {
public function __construct($userID, $userName) {
//values of these parameters should be passed from Create function
var_dump($userID, $userName);
}
}
Solved:
Thanks to schokocappucino & pozs I fixed it by doing this:
$modelConstruct = new \ReflectionMethod($path, '__construct');
$numParams = $modelConstruct->getNumberOfParameters();
if (count($params) != $numParams) {
$tempArray = array_fill(0, $numParams, '');
$params = ($params + $tempArray);
}
return (new \ReflectionClass($path))->newInstanceArgs($params);
To get the constructor of a class using reflection, use ReflectionClass::getConstructor().
To create a new instance (with the constructor) using an argument list, use ReflectionClass::newInstanceArgs()
return (new ReflectionClass($path))->newInstanceArgs($params);

Categories