get method in JViewLegacy - php

I'm pretty new in Joomla and I am struggling with a method that seems to appear out of thin air.
The problem I am having is an empty variable when it is supposed to be filled by
$items = $this->get('Items');
It is located in the file view.html.php and the class name is
class guruViewguruauthor extends JViewLegacy {}
I am sorry in advance if this is a stupid question!!

You should have a getItems method in your guruauthor model class found in your site models folder.
$items = $this->get('Items');
retrieves the data from the model. If you dont have getItems defined in model or getItems sql is not defined properly you may get an empty object.
Check this link it may help you
https://docs.joomla.org/Special:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_a_model_to_the_site_part
A sample getItems method from one of my component
public function getItems($recursive = false)
{
if (!count($this->_items)) {
// import Joomla Categories library
//if you forget this -> Fatal error: Class 'JCategories' not found in ...
jimport( 'joomla.application.categories' );
$app = JFactory::getApplication();
$options = array();
$options['countItems'] = 20;
//$categories = JCategories::getInstance('Content', $options);
$categories = JCategories::getInstance('eventmanagement', $options);
$this->_parent = $categories->get('root');
if (is_object($this->_parent)) {
$this->_items = $this->_parent->getChildren($recursive);
}
else {
$this->_items = false;
}
}
return $this->_items;
}
This will return list of categories and in view I call this as
$categories = $this->get('Items');

Related

how to manage multi-user permission in codeigniter

what is best way to manage multi user permissions and privileges in codeIgniter framework?
I tried to manage it and its working well. But I have to call one function in every controller. that is I am not want to. the function bellow that get controller name and data through session variable.
function allow_user_permission(){
$ci = & get_instance();
$arr = $ci->session->userdata("userdata")['persissions'];
$array = json_decode($arr);
$controller = $ci->router->fetch_class();
$per = (object) array("label"=>$controller,"val"=>true);
$permission = array($per);
if(isset($array)){
$res = in_array($permission, $array, true);
if ($res ==FALSE)
{
redirect(site_url("dashboard"));
}
}
}
All you need is creating a parent controller and then make your controllers inherit from it. The parent controller is instanciated each time you access any controller. And its constructor runs the security check.
1- Create file application/core/MY_Controller.php (PS: I shorthanded your code)
<?php
class Parent_controller extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->allow_user_permission();
}
public function allow_user_permission()
{
$arr = json_decode($this->session->userdata['persissions']);
$permission = array("label" = >$this->router->fetch_class(), "val" => true);
if (!empty($array) && !in_array($permission, $array, true))
redirect(site_url("dashboard"));
}
}
2- In your controllers, you just need to update the class from which your controller is inheriting and use Parent_controller. example:
class Users extends Parent_controller {
}

Joomla 3.4 PHP basic:About JTable::getInstance in libraries/joomla/table/table.php file

I was trying to read and understand some joomla core PHP code when I came across this function. It is located in libraries/joomla/table/table.php line 268. At the end of the function in line 305, it returns an object created by $tableClass, what I don't understand is, where is this $tableClass class defined? Following is a complete list of the function:
public static function getInstance($type, $prefix = 'JTable', $config = array())
{
// Sanitize and prepare the table class name.
$type = preg_replace('/[^A-Z0-9_\.-]/i', '', $type);
$tableClass = $prefix . ucfirst($type);
// Only try to load the class if it doesn't already exist.
if (!class_exists($tableClass))
{
// Search for the class file in the JTable include paths.
jimport('joomla.filesystem.path');
$paths = self::addIncludePath();
$pathIndex = 0;
while (!class_exists($tableClass) && $pathIndex < count($paths))
{
if ($tryThis = JPath::find($paths[$pathIndex++], strtolower($type) . '.php'))
{
// Import the class file.
include_once $tryThis;
}
}
if (!class_exists($tableClass))
{
// If we were unable to find the class file in the JTable include paths, raise a warning and return false.
JLog::add(JText::sprintf('JLIB_DATABASE_ERROR_NOT_SUPPORTED_FILE_NOT_FOUND', $type), JLog::WARNING, 'jerror');
return false;
}
}
// If a database object was passed in the configuration array use it, otherwise get the global one from JFactory.
$db = isset($config['dbo']) ? $config['dbo'] : JFactory::getDbo();
// Instantiate a new table class and return it.
return new $tableClass($db);
}
You can find JTable classes in tables subfolder in administration part of any component. Each file contain table class which extends from JTable class. You don't have override this method getInstance.
In fact JTable can be very simple. Some example:
class XXXTableCity extends JTable
{
/**
* Constructor
*
* #param object Database connector object
*/
function __construct( &$db ) {
parent::__construct('#__xxx_cities', 'id', $db);
}
}

Attempting to access private variable via __get() method returns null

Using PHP 5.3, I am currently writing an MVC application and need to extract the data that was passed in to a model for validation, to send back to the view for repopuating a form on error.
The fields in the model are marked private and can only be accessed if they appear in a list of fieldNames (so controllers can't attempt to change the contents of other 'business' fields in the class.
In the controller area marked 'BUG' below, attempting to access the private field just results in the array item being created but set to null, not the value. While in my debugger, if I inspect the field of the source ($templateM->$field) it shows the correct value.
What's going on?
In the model base class:
class model {
protected $fieldNames;
public function __get($name)
{
if ($name === 'fieldNames')
return $this->fieldNames; // Special exception for getting the list of fields
if ($name === 'errorList')
return $this->errorList; // special exception for getting the current errors
if (in_array($name, (array)$this->fieldNames))
return $this->$name;
else
throw new Exception('Invalid access to private model field');
}
}
In the model:
class template extends model
{
function __construct()
{
parent::__construct();
$this->fieldNames = new immutableArray(array('id', 'etc'));
}
private $id = 0;
private $etc = 1;
}
In the controller:
class templateManager extends controller
{
function create()
{
// Validate form data
$templateM = getModel('template');
$templates = array();
$bodyData = array();
$bodyData['showSuccess'] = false;
$result = $templateM->validate();
if ($result)
{
if ($templateM->save())
{
$bodyData['showSuccess'] = true;
}
}
// Load present data (post insert)
$templates = $templateM->getAllAsArray();
$bodyData['errorMessages'] = (array)$templateM->errorList;
$formData = array();
if (count($bodyData['errorMessages']) > 0)
{
foreach($templateM->fieldNames as $field)
{
$formData[$field] = $templateM->$field; // <- BUG
}
}
$bodyData['formData'] = $formData;
$bodyData['templateData'] = $templates;
$this->_drawPage($bodyData);
}
Actually i would recommend for you to stop abusing __get(). You already have too many if's in it, and that list will get only longer and longer. Better to make proper getter and setter methods.
AS for the cause of your problems: the Model::__get() cannot access the private variables. It will work if you define them as protected.
Additionally, you might find this rant useful. At least the "side notes" part of it.

Zend_Db_Table_Row_Abstract Extended Row Class Not Functioning

I'm using the Zend_Db framework, and I've run into a snag. I'm trying to add custom handling to the column naming at the row level, but it's failing to invoke my function for some reason.
I've stripped down the problem to simply try and figure out if the underlying "Row" class is ever even created. From what I can tell, it isn't.
Here's what I've got:
// this class functions correctly; I get "table" written to my output
class DHR_Table extends Zend_Db_Table_Abstract
{
protected $_rowClass = 'DHR_Row';
function __construct(){
echo "table";
parent::__construct();
}
}
// this class never gets called, at least not that is evident from the constructor echo
class DHR_Row extends Zend_Db_Table_Row_Abstract
{
protected $inflector = null;
function __construct(){
echo "row";
parent::__construct();
}
}
// this is the actual implementation class that uses these two:
class Application_Model_DbTable_Applicants extends DHR_Table
{
protected $_name = 'applicants';
}
My output includes some data (excluded from this post, but part of the "Applicants" class) and "table", but no "row". Any ideas why this might be happening? Version 1.11.11 of the Zend framework.
[Edit]
Here's the usage:
class ApplicantsController extends DHR_RestController
{
public function indexAction()
{
$applicants = new Application_Model_DbTable_Applicants();
$result = $applicants->fetchAll();
$this->success($result);
}
protected function success($data, $code = 200)
{
if(is_a($data, 'Zend_Db_Table_Rowset')){
// we could do some pagination work here
$data = $data->toArray();
}
$this->setResponseCode($code)->appendBody(Zend_Json::encode(array(
'success'=>true,
'data' => $data
)));
}
}
I would expect to at least have some method on the row class invoked when returning the serialized results...
[Update]
If I use "fetchRow" everything works as expected; fetchAll simply does't do the conversion to the underlying object type.
I was just looking at the code for the row/abstract class.
Try setting a value for $_tableClass. $_tableClass = 'DHR_Table';
I'm afraid that won't work as it looks like Zend/Db/Table/Row/Abstract.php is going to look for a table definition no matter what, so the level of abstraction you seem to be after may not be possible without further extending.
//excerpt from __construct Zend/Db/Table/Row/Abstract.php
public function __construct(array $config = array())
{
if (isset($config['table']) && $config['table'] instanceof Zend_Db_Table_Abstract) {
$this->_table = $config['table'];
$this->_tableClass = get_class($this->_table);
} elseif ($this->_tableClass !== null) {
$this->_table = $this->_getTableFromString($this->_tableClass);
}
// cont...
// Retrieve primary keys from table schema
if (($table = $this->_getTable())) {
$info = $table->info();
$this->_primary = (array) $info['primary'];
}
$this->init();

Codeigniter - return my model object instead of stdClass Object

Not sure the best way of phrasing this so bear with me.
Within Codeigniter I can return a record set of my object no problem but this is returned as a stdClass object not as an "model" object (for example a Page Object) which I can then use to make use of other methods within that model.
Am I missing a trick here? Or is this the standard functionality within CI?
Yes, basically in order for this to work you need to declare your Model objects properties class-wide, and refer to $this being the current model object.
class Blogmodel extends CI_Model {
var $title = '';
var $content = ''; // Declare Class wide Model properties
var $date = '';
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_entry()
{
$query = $this->db->query('query to get single object');
$db_row = $query->row(); //Get single record
$this->title = $db_row->title;
$this->content = $db_row->content; //Populate current instance of the Model
$this->date = $db_row->date;
return $this; //Return the Model instance
}
}
I believe get_entry() will return an object type Blogmodel.
You don't need sth like:
$this->title = $db_row->title;
$this->content = $db_row->content; //Populate current instance of the Model
$this->date = $db_row->date;
Just put to the result() method ur model:
result(get_class($this));
or
result(get_called_class());
And you'll get instance of ur model!
My solution to this problem consisted of a combination of jondavidjohn's answer and mkoistinen's comment.
According to the CodeIgniter documentation:
You can also pass a string to result() which represents a class to
instantiate for each result object (note: this class must be loaded)
Armed with that knowledge, we can rewrite jondavidjohn's solution in this way:
class Blogmodel extends CI_Model {
var $title = '';
var $content = ''; // Declare Class wide Model properties
var $date = '';
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_entry()
{
$query = $this->db->query('query to get single object');
$blogModel = $query->row('Blogmodel'); //Get single record
return $blogModel; //Return the Model instance
}
}

Categories