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()
Related
I am starting my game with CodeIgniter and I have a problem - I would like to download the ID - of the product from the database so that it will be passed to the URL address:
Example address:
http://localhost/crm-SEO/api/admin/domains/{{ID in database}}/notes
When I have other methods like:
domains/GET/6
domains/update/6
Everything works fine for me, but I can not grasp it that I have domains/{{ID}}/
My code i models:
public function get( $id = false)
{
if ( $id == false ) {
$q = $this->db->get('domains');
$q = $q->result();
}
else{
$this->db->where('id', $id);
$q = $this->db->get('domains');
$q = $q->row();
}
return $q;
}
public function update($domain)
{
$this->db->where('id', $domain['id'] );
$this->db->update('domains', $domain);
}
public function create($domain)
{
$this->db->insert('domains', $domain);
}
public function delete($domain)
{
$this->db->where('id', $domain['id'] );
$this->db->delete('domains');
}
My code in controller:
public function __construct()
{
parent::__construct();
$post = file_get_contents('php://input');
$_POST = json_decode($post,true);
$this->load->model('admin/domains_model');
}
public function get($id = false)
{
$result = $this->domains_model->get($id);
echo '{"records":' . json_encode( $result ) . '}';
}
public function update()
{
$domain = $this->input->post('domain');
$this->domains_model->update($domain);
}
public function create()
{
$domain = $this->input->post('domain');
$this->domains_model->create($domain);
}
public function delete()
{
$domain = $this->input->post('domain');
$this->domains_model->delete($domain);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I try to learn how to make MVC model, but i have the following errors:
Notice: Sorry no method prepare has been found in ......./pdodatabasehandler.php 27
Fatal error: Call to a member function execute() on null in ..../abstractmodel.php 98
databasehandler.php
<?php
namespace BATRAHOSTMVC\Lib\Database;
/**
* Description of DatabaseHandler
*
* #author Mohamed Hassan Elmetwaly
* 25-03-2017
* mhe.developer#gmail.com
*/
abstract class DatabaseHandler {
const DATABASE_DRIVER_POD = 1;
const DATABASE_DRIVER_MYSQLI = 2;
private function __construct() {
}
abstract protected static function init();
abstract protected static function getInstance();
public static function factory()
{
// $driver = DATABASE_CONN_DRIVER;
// if($driver == self::DATABASE_DRIVER_POD)
// {
return PDODatabaseHandler::getInstance();
// } else if ($driver == self::DATABASE_DRIVER_MYSQLI)
// {
// return MySQLiDatabaseHandler::getInstance();
// }
}
}
pdodatabasehandler.php
<?php
namespace BATRAHOSTMVC\Lib\Database;
/**
* Description of pdodatabasehandler
* #author Mohamed Hassan Elmetwaly
* 25-03-2017
* mhe.developer#gmail.com
*/
class PDODatabaseHandler extends DatabaseHandler
{
private static $_instance;
private static $_handler;
private function __construct() {
self::init();
}
//public function __call($name, $arguments) {}
public function __call($name, $arguments) {
if(method_exists($this, $name))
{
$this->$name($arguments);
} else {
trigger_error('Sorry no method '. $name. ' has been found');
}
}
protected static function init(){
try{
self::$_handler = new \PDO(
'mysql:host='.DATABASE_HOST_NAME.';dbname='.DATABASE_DB_NAME,DATABASE_USER_NAME,
DATABASE_PASSW0RD);
//var_dump(self::$_handler);
//self::$_handler = new pdo("mysql:host=localhost; dbname=test", 'root', 'rootbootroot');
//return 'Connected';
} catch (\PDOException $e)
{
echo $e->getMessage( ) ." | ". $e->getCode( ) ;
}
}
public static function getInstance() {
if(self::$_instance === null){
self::$_instance = new self();
}
return self::$_instance;
}
}
abstractmodel.php
<?php
namespace BATRAHOSTMVC\Models;
use BATRAHOSTMVC\Lib\Database\DatabaseHandler;
//echo DATABASE_DB_NAME;
/**
* Description of abstractmodel
* #author Mohamed Hassn Elmetwaly (25-03-2017)
* mhe.developer#gmail.com
*/
class AbstractModel
{
const DATA_TYPE_BOOL = \PDO::PARAM_BOOL;
const DATA_TYPE_STR = \PDO::PARAM_STR;
const DATA_TYPE_INT = \PDO::PARAM_INT;
const DATA_TYPE_DECIMAL = 4;
const DATA_TYPE_DATE = 5;
/*
public static function viewTableSchema()
{
return static::$tableSchema;
}
*
*/
// we make path by reference
private function prepareValues(\PDOStatement &$stmt)
{
foreach (static::$tableSchema as $columnName => $type)
{
if($type == 4)
{
$sanitizedValue = filter_var($this->$columnName, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$stmt->bindValue(":{$columnName}", $sanitizedValue);
}
else
{
$stmt->bindValue(":{$columnName}", $this->$columnName, $type);
}
}
}
private static function buildNameParametersSQL()
{
$nameParams = '';
//$columnName (Column Name) => $type (Column datatype)
foreach (static::$tableSchema as $columnName => $type)
{
$nameParams .= $columnName. ' = :'.$columnName. ', ';
}
return trim($nameParams, ', ');
}
private static function create()
{
//global $connection;
$sql = 'INSERT INTO '. static::$tableName . ' SET '. self::buildNameParametersSQL();
$stmt = DatabaseHandler::factory()->prepare($sql);
$this->prepareValues($stmt);
return $stmt->execute(); // true of false
}
private static function update()
{
// global $connection;
$sql = 'UPDATE '. static::$tableName . ' SET '. self::buildNameParametersSQL(). ' WHERE '. static::$primaryKey .' = '.$this->{static::$primaryKey};
// $stmt = $connection->prepare($sql);
//$stmt = DatabaseHandler::factory()->prepare($sql);
$stmt = DatabaseHandler::factory()->prepare($sql);
$this->prepareValues($stmt);
return $stmt->execute(); // true of false
}
public function save()
{
return $this->{static::$primaryKey} === null ? $this->create() : $this->update();
}
public static function delete()
{
// global $connection;
$sql = 'DELETE FROM '. static::$tableName . ' WHERE '. static::$primaryKey .' = '.$this->{static::$primaryKey};
// $stmt = $connection->prepare($sql);
$stmt = DatabaseHandler::factory()->prepare($sql);
return $stmt->execute(); // true of false
}
public static function getAll()
{
// global $connection;
$sql = 'SELECT * FROM '. static::$tableName;
//$stmt = $connection->prepare($sql);
$stmt = DatabaseHandler::factory()->prepare($sql);
//return $connection->execute() === true ? $stmt->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, 'Employee', array('name', 'age', 'address', 'tax', 'salary')) : false;
//using fetchAll with this paramaters return values as OBJECT Of class which returned by get_called_calss() which called this method
$stmt->execute();
$result = $stmt->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, get_called_class(), array_keys(static::$tableSchema));
return is_array($result) && !empty($result) === true ? $result : false;
}
public static function getByPk($pk)
{
//global $connection;
$sql = 'SELECT * FROM '. static::$tableName. ' WHERE '. static::$primaryKey .' = '.$pk;
//$stmt = $connection->prepare($sql);
//$stmt = DatabaseHandler::factory()->prepare($sql);
$stmt = DatabaseHandler::factory()->prepare($sql);
//return $connection->execute() === true ? $stmt->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, 'Employee', array('name', 'age', 'address', 'tax', 'salary')) : false;
//using fetchAll with this paramaters return values as OBJECT Of class which returned by get_called_calss() which called this method
if($connection->execute() === true)
{
$obj = $stmt->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, get_called_class(), array_keys(static::$tableSchema));
return array_shift($obj);
}
return false;
}
public static function get($sql, $options = array())
{
/*
* example:
* $emps = Employee::get(
* 'SELECT name, age FROM employees WHERE age = :age',
* array(
* 'age' => array(Employee::DATA_TYPE_INT, 34)
* )
* )
* var_dump($emps)
*/
//global $connection;
//$stmt = $connection->prepare($sql);
$stmt = DatabaseHandler::factory()->prepare($sql);
if(!empty($options))
{
foreach ($options as $columnName => $type)
{
//$type[0] = datatype, $type[1] = columname
if($type[0] == 4)
{
$sanitizedValue = filter_var($type[1], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$stmt->bindValue(":{$columnName}", $sanitizedValue);
}
else
{
$stmt->bindValue(":{$columnName}", $type[1], $type[0]);
}
}
}
$stmt->execute();
$result = $stmt->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, get_called_class(), array_keys(static::$tableSchema));
return is_array($result) && !empty($result) === true ? $result : false;
/*
if(method_exists(get_called_class(), '__construct')){
$result = $stmt->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, get_called_class(), array_keys(static::$tableSchema));
//return is_array($result) && !empty($result) === true ? $result : false;
} else {
$result =$stmt->fetchAll(\PDO::FETCH_CLASS, get_called_class());
}
if((is_array($result) && !empty($result))){
$generator = function() use ($result){};
return $generator;
}
return false;
*/
}
}
employeecontroller.php
<?php
/**
* Description of abstractcontroller
*
* #author Mohamed Hassn Elmetwaly (25-03-2017)
* mhe.developer#gmail.com
*/
namespace BATRAHOSTMVC\Controllers;
use BATRAHOSTMVC\Models\EmployeeModel;
class EmployeeController extends AbstractController
{
public function defaultAction()
{
//EmployeeModel::getAll();
var_dump(EmployeeModel::getAll());
$this->_view();
}
}
employeemodel.php
<?php
namespace BATRAHOSTMVC\Models;
//use BATRAHOSTMVC\Models\AbstractModel;
//use BATRAHOSTMVC\Models\AbstractModel;
/**
* Description of employee
* #author Mohamed Hassn Elmetwaly (25-03-2017)
* mhe.developer#gmail.com
*/
class EmployeeModel extends AbstractModel
{
public $id;
public $name;
public $age;
public $address;
public $tax;
public $salary;
public static $db;
protected static $tableName = 'employees';
protected static $tableSchema = array(
'name' => self::DATA_TYPE_STR,
'age' => self::DATA_TYPE_INT,
'address' => self::DATA_TYPE_STR,
'tax' => self::DATA_TYPE_DECIMAL,
'salary' => self::DATA_TYPE_DECIMAL
);
protected static $primaryKey = 'id';
public function __construct($name, $age, $address, $tax, $salary) {
$this->name = $name;
$this->age = $age;
$this->address = $address;
$this->tax = $tax;
$this->salary = $salary;
}
public function __get($prop){
$this->$prop;
}
public function getTableName(){
return self::$tableName;
}
}
autoload.php
<?php
namespace BATRAHOSTMVC\LIB;
/*
* Applcation Constants
*/
/*
define('DS', DIRECTORY_SEPARATOR);
define('APP_PATH', dirname(realpath(__FILE__)).DS.'..');
define('PS', PATH_SEPARATOR);
define('CONTROLLER_PATH', APP_PATH.DS.'controllers');
define('MODEL_PATH', APP_PATH.DS.'models');
//echo CONTROLLER_PATH;
$path = get_include_path().PS.CONTROLLER_PATH.PS.MODEL_PATH;
set_include_path($path);
*/
class Autoload
{
public static function autoload($classname)
{
/* in Explanation */
$classname = str_replace('BATRAHOSTMVC', '',$classname);
$classname = str_replace('\\', '/', $classname);
$classname = $classname.'.php';
$classname = strtolower($classname);
if(file_exists(APP_PATH.$classname))
{
require_once APP_PATH.$classname;
}
/*
$class = str_replace('\\', '/', $classname);
$classFile = APP_PATH.DIRECTORY_SEPARATOR.strtolower($class).'.php';
if(file_exists($classFile))
{
require $classFile;
}
else
{
return;
}
*/
}
}
spl_autoload_register(__NAMESPACE__.'\Autoload::autoload');
frontcontroller.php
<?php
namespace BATRAHOSTMVC\LIB;
class FrontController
{
const NOT_FOUND_ACTION = 'notFoundAction';
const NOT_FOUND_CONTROLLER = 'BATRAHOSTMVC\Controllers\NotFoundController';
private $_controller = 'index';
private $_action = 'default';
private $_params = array();
public function __construct() {
$this->_parseUrl();
}
private function _parseUrl()
{
$url = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH),'/'), 3);
var_dump($url);
if(isset($url[0]) && $url[0] !='')
{
$this->_controller = $url[0];
}
if(isset($url[1]) && $url[1] !='')
{
$this->_action = $url[1];
}
if(isset($url[2]) && $url[2] !='')
{
$this->_params = explode('/', $url[2]);
}
// #list($this->_controller, $this->_action, $this->_params) = explode('/', trim($url, '/'),3);
// $this->_params = explode('/', $this->_params);
var_dump($this);
}
public function dispatch()
{
$controllerClassName = 'BATRAHOSTMVC\Controllers\\'.ucfirst($this->_controller).'Controller';
$actionName = $this->_action.'Action';
if(!class_exists($controllerClassName))
{
$controllerClassName = self::NOT_FOUND_CONTROLLER;
}
$controller = new $controllerClassName();
if(!method_exists($controller, $actionName))
{
$this->_action = $actionName = self::NOT_FOUND_ACTION;
}
$controller->setController($this->_controller);
$controller->setAction($this->_action);
$controller->setParams($this->_params);
$controller->$actionName();
}
}
I attached my files in the following link
http://www.mediafire.com/file/mdbxj5o3f6hd3gz/mvcyahia%285-4-2017%29.rar
Thanks in advance
public static function getInstance() {
if(self::$_instance === null){
self::$_instance = new self();
}
// here was the confusing the old value was return self::$_instance
return self::$_handler;
}
Your database / query object is null. So find how you call the database object so you can call its method.
Your code shows no prepare() method defined for your db class.
You are setting your PDODatabaseHandler::_handler property to the PDO, but when you are returning self(). Get it?
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;
}
I have a class that translate language array base. So the problem is that the language does not change base on a cookie value.
this function should set the language value but it does not. it seems that no matter what i do i always get "ar" as a self::$currlang value. how can i correct this issue?
public function _set(){
if( $_COOKIE['defaultLang'] != '' ) {
self::$currlang = $_COOKIE['defaultLang'];
} else {
//this is the default language
self::$currlang = 'ar';
}
}
here is my code
thanks for your help :)
<?php
include('../langs/english.php');
include('../langs/arabic.php');
class Translator{
private static $strs = array();
private static $currlang = "";
public function _set(){
if( $_COOKIE['defaultLang'] != '' ) {
self::$currlang = $_COOKIE['defaultLang'];
} else {
//this is the default language
self::$currlang = 'ar';
}
}
public static function loadTranslation($lang, $strs){
if (empty(self::$strs[$lang]))
self::$strs[$lang] = array();
self::$strs[$lang] = array_merge(self::$strs[$lang], $strs);
}
public static function setDefaultLang($lang){
self::$currlang = $lang;
}
public static function getDefaultLang(){
return self::$currlang;
}
public static function translate($key, $lang=""){
if ($lang == ""){
$lang = self::$currlang;
}
$str = self::$strs[$lang][$key];
if (empty($str)){
//$str = "$lang.$key";
$str = 'Language "'. $lang . '", '. $key . ' is not defined.';
}
return $str;
}
public static function freeUnused(){
foreach(self::$strs as $lang => $data){
if ($lang != self::$currlang){
$lstr = self::$strs[$lang]['langname'];
self::$strs[$lang] = array();
self::$strs[$lang]['langname'] = $lstr;
}
}
}
public static function getLangList(){
$list = array();
foreach(self::$strs as $lang => $data){
$h['name'] = $lang;
$h['desc'] = self::$strs[$lang]['langname'];
$h['current'] = $lang == self::$currlang;
$list[] = $h;
}
return $list;
}
public static function &getAllStrings($lang){
return self::$strs[$lang];
}
}
?>
The _set() magic method works with the -> operator, which works with instantiated objects. You can't use static member variables with instantiated objects, it's one or the other.
I am new to Zend and have been attempting to follow the Zend Quick Start Guide's example of using Data Mappers and extending Zend_Db_Table_Abstract. I think I've grasped the general concepts, but I am now wondering, how I would go about modifying the guide's example code to allow for multiple tables.
Here is the part of the code I am currently interested in modifying:
protected $_dbTable;
public function setDbTable($dbTable)
{
if (is_string($dbTable)) {
$dbTable = new $dbTable();
}
if (!$dbTable instanceof Zend_Db_Table_Abstract) {
throw new Exception('Invalid table data gateway provided');
}
$this->_dbTable = $dbTable;
return $this;
}
public function getDbTable()
{
if (null === $this->_dbTable) {
$this->setDbTable('Application_Model_DbTable_Guestbook');
}
return $this->_dbTable;
}
I have changed it to this:
protected $_dbTables;
public function setDbTable($dbTable, $tableName)
{
if (is_string($dbTable)) {
$dbTable = new $dbTable();
}
if (!$dbTable instanceof Zend_Db_Table_Abstract) {
throw new Exception('Invalid table data gateway provided');
}
$this->_dbTables[$tableName] = $dbTable;
return $this;
}
public function getDbTables()
{
if (null === $this->_dbTables) {
$this->setDbTable('Application_Model_DbTable_Courses', 'courses');
$this->setDbTable('Application_Model_DbTable_CourseTimes', 'course_times');
}
return $this->_dbTables;
}
Is this a correct way to go about implementing multiple tables within the Data Mapper pattern or would you do it differently? Thanks for your help in advance!
Assuming that you want to return data from related tables, you should either add queries with joins to one Zend_Db_Table or use Zend_Db_Table_Relationships to fetch associated data. The benefit of using Joins is that you will only do one query over many when using Relationships. The drawback is that joined tables wont return Zend_Db_Table_Row objects (iirc), but since you are going to map them onto your Domain objects anyway, it's not that much of an issue.
Structurally, you can do like I suggested in How to change Zend_Db_Table name within a Model to insert in multiple tables. Whether you create a Gateway of Gateways or simply aggregate the Table Gateways in the DataMapper directly is really up to you. Just compose them as you see fit.
I'm not sure if it's the best practice, but, this is my abstract mapper:
<?php
abstract class Zf_Model_DbTable_Mapper
{
protected $_db;
protected $_dbTable = null;
protected $_systemLogger = null;
protected $_userLogger = null;
public function __construct()
{
$this->_systemLogger = Zend_Registry::get('systemLogger');
$this->_userLogger = Zend_Registry::get('userLogger');
// Set the adapter
if(null !== $this->_dbTable)
{
$tableName = $this->_dbTable;
$this->_db = $this->$tableName->getAdapter();
}
}
public function __get($value)
{
if(isset($this->$value))
{
return $this->$value;
}
$dbTable = 'Model_DbTable_' . $value;
$mapper = 'Model_' . $value;
if(class_exists($dbTable))
{
return new $dbTable;
}
elseif(class_exists($mapper))
{
return new $mapper;
}
else
{
throw new Exception("The property, DbTable or Mapper \"$value\" doesn't exists");
}
}
public function __set($key,$value)
{
$this->$key = $value;
}
public function getById($id)
{
$resource = $this->getDefaultResource();
$id = (int)$id;
$row = $resource->fetchRow('id =' . $id);
if (!$row) {
throw new Exception("Count not find row $id");
}
return $row;
}
public function getAll()
{
$resource = $this->getDefaultResource();
return $resource->fetchAll()->toArray();
}
public function save(Zf_Model $Model)
{
$dbTable = $this->getDefaultResource();
$data = $Model->toArray();
if(false === $data) return false;
if(false === $Model->isNew())
{
if(1 == $dbTable->update($data, 'id =' . (int)$Model->getId()))
{
return $Model;
}
}
else
{
$id = $dbTable->insert($data);
if($id)
{
$Model->setId($id);
return $Model;
}
}
return false;
}
public function remove($id)
{
return $this->getDefaultResource()->delete('id =' . (int) $id);
}
protected function getDefaultResource()
{
if(empty($this->_dbTable))
{
throw new Exception('The $_dbTable property was not set.');
}
$classname = 'Model_DbTable_' . $this->_dbTable;
if(!class_exists($classname))
{
throw new Exception("The Model_DbTable_\"$classname\" class was not found.");
}
return new $classname;
}
protected function getDefaultModel()
{
return current($this->_models);
}
protected function getResources()
{
return $this->_resources;
}
}
And this is one for my implemented mappers:
<?php
class Model_TwitterPostsMapper extends Zf_Model_DbTable_Mapper
{
/*
* Data Source
* #var string Zend_Db_Table name
*/
protected $_dbTable = 'TwitterPosts';
public function recordExists($Item)
{
$row = $this->TwitterPosts->fetchRow($this->TwitterPosts->select()->where('status_id =?', $Item->getSource()->getStatusId()));
if($row)
{
return $row->id;
}
return false;
}
public function getLastUpdate($options)
{
$select = $this->TwitterPosts->select()
->setIntegrityCheck(false)
->from(array('t' => 'twt_tweets'), 't.created_at')
->join(array('u' => 'twt_users'), 't.user_id = u.id', '')
->order('t.created_at DESC');
if($options['user_id'])
{
$select->where("t.user_id = ?", $options['user_id']);
}
if($options['terms'])
{
if(is_array($options['terms']))
{
$condition = '';
foreach($options['terms'] as $i => $term)
{
$condition .= ($i > 0) ? ' OR ' : '';
$condition .= $this->getAdapter()->quoteInto('content LIKE ?',"%$term%");
}
if($condition)
{
$select->where($condition);
}
}
}
return $this->TwitterPosts->fetchRow($select)->created_at;
}
public function getSinceId($term = null)
{
$select = $this->TwitterPosts->select()->setIntegrityCheck(false)
->from('twt_tweets_content', 'status_id')
->where('MATCH(content) AGAINST(? IN BOOLEAN MODE)', "$term")
->order('status_id ASC')
->limit(1);
//echo $select; exit;
$tweet = $this->TwitterPosts->fetchRow($select);
if(null !== $tweet) return $tweet->status_id;
return 0;
}
public function getAllByStatusId($statuses_id)
{
$select = $this->TwitterPosts->select()
->setIntegrityCheck(false)
->from(array('t' => 'twt_tweets'), array('t.id', 't.user_id', 't.status_id','t.user_id'))
->join(array('u' => 'twt_users'), 't.user_id = u.id', array('u.screen_name', 'u.profile_image'))
->where('status_id IN(?)', $statuses_id);
$rows = $this->TwitterPosts->fetchAll($select);
$Posts = array();
foreach($rows as $row)
{
// Here we populate the models only with the specific method return data
$data = $row->toArray();
$Post = new Model_TwitterPost($data['id']);
$Post->populate($data);
$User = new Model_TwitterUser($data['user_id']);
$User->populate($data);
$Post->setUser($User);
$Posts[] = $Post;
}
return $Posts;
}
public function getAllSince($since_id)
{
$select = $this->TwitterPosts->select()
->setIntegrityCheck(false)
->from(array('t' => 'twt_tweets'), array('t.status_id','t.user_id'))
->join(array('u' => 'twt_users'), 't.user_id = u.id', array('u.screen_name', 'u.profile_image'))
->where('status_id > ?', $since_id)
->order('t.datetime DESC');
$rows = $this->TwitterPosts->fetchAll($select);
$Posts = array();
foreach($rows as $row)
{
// Here we populate the models only with the specific method return data
// TODO: This is not a truly lazy instatiation, since there's no way to get the not setted properties
$data = $row->toArray();
$Post = new Model_TwitterPost($data);
$User = new Model_TwitterUser($data);
$Post->setUser($User);
$Posts[] = $Post;
}
return $Posts;
}
public function getTotalRatedItems($options)
{
$options = $this->prepareOptions($options);
$select = $this->TwitterPosts->select()
->setIntegrityCheck(false)
->from(array('t' => 'twt_tweets'), array('COUNT(DISTINCT t.id) AS total','r.rate'))
->join(array('u' => 'twt_users'), 't.user_id = u.id', '')
->join(array('r' => 'twt_tweets_rate'), 't.id = r.tweet_id', array('r.rate'))
->group('r.rate')
->order('t.datetime DESC');
$select = $this->prepareSelect($select, $options);
$rates = $this->TwitterPosts->fetchAll($select)->toArray();
$itemsRated = array('Green' => 0, 'Yellow' => 0, 'Orange' => 0, 'Red' => 0, 'Gray' => 0);
foreach ($rates as $rate)
{
$itemsRated[$rate['rate']] = $rate['total'];
}
return $itemsRated;
}
public function getUsersActivity($options)
{
$options = $this->prepareOptions($options);
$select = $this->TwitterPosts->select()
->setIntegrityCheck(false)
->from(array('t' => 'twt_tweets'), array('COUNT(DISTINCT t.id) AS total','DATE(t.datetime) AS datetime'))
->join(array('u' => 'twt_users'), 't.user_id = u.id', '')
->joinLeft(array('r' => 'twt_tweets_rate'), 't.id = r.tweet_id', '')
->group('t.user_id')
->order('t.datetime DESC');
$select = $this->prepareSelect($select, $options);
$activity = $this->TwitterPosts->fetchAll($select)->toArray();
return $activity;
}
public static function prepareOptions($options)
{
if(!is_array($options))
{
$options = array();
}
date_default_timezone_set('America/Sao_Paulo');
if(Zend_Date::isDate($options['start_date']))
{
$date = new Zend_Date($options['start_date']);
$date->setTime('00:00:00');
$date->setTimezone('UTC');
$options['start_date'] = $date->toString('yyyy-MM-dd HH:mm:ss');
}
if(Zend_Date::isDate($options['end_date']))
{
$date = new Zend_Date($options['end_date']);
$date->setTime('23:59:59');
$date->setTimezone('UTC');
$options['end_date'] = $date->toString('yyyy-MM-dd HH:mm:ss');
}
date_default_timezone_set('UTC');
$options['mainTerms'] = array();
if(!empty($options['terms']) && !is_array($options['terms']))
{
$options['mainTerms'] = explode(' ', $options['terms']);
}
if(!is_array($options['terms']))
{
$options['terms'] = array();
}
if($options['group_id'] || $options['client_id'])
{
$TwitterSearches = new Model_DbTable_TwitterSearches();
$options['terms'] = array_merge($TwitterSearches->getList($options),$options['terms']);
if(empty($options['terms']))
{
$options['terms'] = array();
}
}
return $options;
}
public static function prepareSelect($select, $options)
{
if($options['start_date'])
{
$select->where('t.datetime >= ?', $options['start_date']);
}
if($options['end_date'])
{
$select->where('t.datetime <= ?', $options['end_date']);
}
foreach($options['mainTerms'] as $mainTerm)
{
$select->where('t.content LIKE ?', "%$mainTerm%");
}
if($options['user_id'])
{
$select->where("t.user_id = ?", $options['user_id']);
}
if($options['terms'])
{
$select->where('MATCH (t.content) AGASINT(?)', $options['terms']);
}
if($options['rate'])
{
if($options['rate'] == 'NotRated')
{
$select->where('r.rate IS NULL');
}
else
{
$select->where('r.rate = ?', $options['rate']);
}
}
if($options['last_update'])
{
$select->where('t.created_at > ?', $options['last_update']);
}
if($options['max_datetime'])
{
$select->where('t.created_at < ?', $options['max_datetime']);
}
return $select;
}
}
The Model:
<?php
class Model_TwitterPost extends Zf_Model
{
private $_name = 'twitter';
protected $_properties = array(
'id',
'status_id',
'user_id',
'content'
);
protected $_User = null;
public function setUser(Zf_Model $User)
{
$this->_User = $User;
}
public function getUser()
{
return $this->_User;
}
public function getPermalink()
{
return 'http://twitter.com/' . $this->screen_name . '/' . $this->status_id;
}
public function hasTerm($term)
{
if(preg_match("/\b$term\b/i", $this->getContent()))
{
return true;
}
return false;
}
public function getEntityName()
{
return $this->_name;
}
public function getUserProfileLink()
{
return $this->getUser()->getProfileLink() . '/status/' . $this->getStatusId();
}
}
Abstract model (Generic Object):
<?php
abstract class Zf_Model
{
protected $_properties = array();
protected $_modified = array();
protected $_data = array();
protected $_new = true;
protected $_loaded = false;
public function __construct($id=false)
{
$id = (int)$id;
if(!empty($id))
{
$this->_data['id'] = (int)$id;
$this->setNew(false);
}
}
public function populate($data)
{
if(is_array($data) && count($data))
{
foreach($data as $k => $v)
{
if(in_array($k,$this->_properties))
{
$this->_data[$k] = $v;
}
}
}
$this->setLoaded(true);
}
public function setNew($new=true)
{
$this->_new = (bool)$new;
}
public function isNew()
{
return $this->_new;
}
public function setLoaded($loaded = true)
{
$this->_loaded = (bool)$loaded;
}
public function isLoaded()
{
return $this->_loaded;
}
public function __call($methodName, $args) {
if(method_exists($this, $methodName))
{
return $this->$methodName($args);
}
$property = $methodName;
if (preg_match('~^(set|get)(.*)$~', $methodName, $matches))
{
$filter = new Zend_Filter_Word_CamelCaseToUnderscore();
$property = strtolower($filter->filter($matches[2]));
if(in_array($property, $this->_properties))
{
if('set' == $matches[1])
{
$this->_data[$property] = $args[0];
if(true === $this->isLoaded())
{
$this->_modified[$property] = true;
}
return $this;
}
elseif('get' == $matches[1])
{
if(array_key_exists($property, $this->_data))
{
return $this->_data[$property];
}
throw new Exception("The property $property or $methodName() method was not setted for " . get_class($this));
}
}
}
throw new Exception("The property '$property' doesn't exists.");
}
public function __get($key)
{
if(isset($this->_data[$key]))
{
return $this->_data[$key];
}
return $this->$key;
}
public function __set($key,$value)
{
if(array_key_exists($key,$this->_properties))
{
$this->_data[$key] = $value;
return;
}
$this->$key = $value;
}
public function getId()
{
return (!$this->_data['id']) ? null : $this->_data['id'];
}
public function toArray()
{
// If it's a new object
if(true === $this->isNew())
{
return $this->_data;
}
// Else, if it's existing object
$data = array();
foreach($this->_modified as $k=>$v)
{
if($v)
{
$data[$k] = $this->_data[$k];
}
}
if(count($data))
{
return $data;
}
return false;
}
public function reload()
{
$this->_modified = array();
}
}