Now I am learning CodeIgniter_2.1.4 but I got a php error;
I have a my_model.php file in /data/www/application/core
<?php
class MY_Model extends CI_Model {
const DB_TABLE = 'abstract';
const DB_TABLE_PK = 'abstract';
private function insert() {
$this->db->insert($this::DB_TABLE, $this);
$this->{$this::DB_TABLE_PK} = $this->db->insert_id();
}
private function update() {
$this->db->update($this::DB_TABLE, $this, $this::DB_TABLE_PK);
}
public function populate($row) {
foreach($row as $key => $value) {
$this->$key = $value;
}
}
public function load($id) {
$query = $this->db->get_where($this::DB_TABLE, array(
$this::DB_TABLE_PK => $id,
));
$this->populate($query->row());
}
public function delete(){
$this->db->delete($this::DB_TABLE, array(
$this::DB_TABLE_PK => $this->{$this::DB_TABLE_PK},
));
unset($this->{$this::DB_TABLE_PK});
}
public function save(){
if(isset($this->{$this::DB_TABLE_PK})) {
$this->update();
}
else {
$this->insert();
}
}
public function get($limit = 0, $offset = 0) {
if($limit) {
$query = $this->db->get($this::DB_TABE, $limit, $offset);
}
else {
$query = $this->db->get($this::DB_TABLE);
}
$ret_val = array();
$class = get_class($this);
foreach ($query->result() as $row) {
$model = new $class;
$model->populate($row);
$ret_val[$row->{$this::DB_TABLE_PK}] = $model;
}
return $ret_val;
}
}
and my domain model is :
<?php
class Publication extends MY_Model {
const DB_TABLE = 'publications';
const DB_TABLE_PK = 'publication_id';
public $publication_id;
public $publication_name;
}
well when I get model in my controller I got this php error:
PHP Fatal error: Class 'MY_Model' not found in /data/www/application/models/publication.php on line 3
I have tried two hours finding the reason but failed ):
I have a my_model.php file in /data/www/application/core
the my_model.php should be renamed to MY_Model.php.
It should be a case-sensitivity issue. Class names must have the first letter capitalized with the rest of the name lowercase.
in your publications.php have the following statement before the class declaration.
require_once "my_model.php";
the error is because you haven't included the definition of My_Model in your publications.php
Related
I'm writing PHPUnit Test with Mockery, (PHP v5.6.32, PHPUnit 3.7.21, Mockery dev-master) and found something which I can't understand about using Mockery::mock and Mockery::namedMocks.
My code is below, and the questions are:
Am I correct to use in LegendTest.php the Mockery::namedMock() instead of Mockery::mock() for SignalsCollection object?
Regarding to documentation about namedMock, I expect that frist argument is the Class name (SignalsCollection) and the second argument should be the extends statement (\ArrayObject) - but in my case I'm getting an error: Mockery\Exception\BadMethodCallException : Received Charts\SignalsCollection::getIterator(), but no expectations were specified, so I'm giving only one argument and this works fine. Why? What am I doing wrong? I'm confused.
Did I missed something in this test case or should I do something different to make tests better?
Signal.php:
class Signal
{
protected $id = 0;
protected $colName = '';
protected $tableName = '';
public function getId()
{
return $this->id;
}
public function setColName($colName)
{
$this->colName = $colName;
return $this;
}
public function setTableName($tableName)
{
$this->tableName = $tableName;
return $this;
}
}
SignalsCollection.php:
class SignalsCollection extends \ArrayObject
{
}
Legend.php
class Legend
{
protected $signalsCollection = null;
protected $graphModel = null;
public function __construct(SignalsCollection $signalsCollection, GraphModel $graphModel)
{
$this->signalsCollection = $signalsCollection;
$this->graphModel = $graphModel;
}
public function getSignalsCollection()
{
return $this->signalsCollection;
}
public function removeSignal(Signal $signal)
{
foreach ($this->signalsCollection as $key => $item) {
if ($item->getId() === $signal->getId()) {
$this->signalsCollection->offsetUnset($key);
break;
}
}
}
}
LegendTest.php:
class LegendTest extends \PHPUnit_Framework_TestCase
{
protected function tearDown()
{
parent::tearDown();
Mockery::close();
}
public function testRemoveSignal()
{
$testSignal = Mockery::mock('\Charts\Signal')
->shouldReceive('setColName', 'setTableName')
->andReturn(Mockery::self())
->mock();
$testSignal
->setColName('testColumnName')
->setTableName('testTableName');
$testSignalSecond = Mockery::mock('\Charts\Signal')
->shouldReceive('setId', 'setColName', 'setTableName')
->andReturn(Mockery::self())
->mock();
$testSignalSecond
->setId(1)
->setColName('testColumnName')
->setTableName('testTableName');
$signalsCollection = Mockery::namedMock('\Charts\SignalsCollection')
->shouldReceive('append', 'offsetUnset')
->andReturn(Mockery::self())
->mock();
$signalsCollection
->append($testSignal)
->append($testSignalSecond);
$legend = new Legend($signalsCollection, Mockery::mock('\Charts\GraphModel'));
$this->assertEquals($signalsCollection, $legend->getSignalsCollection());
$legend->removeSignal($testSignalSecond);
$signalsCollection->offsetUnset(1);
$this->assertEquals( $signalsCollection, $legend->getSignalsCollection() );
}
}
Fatal error: Call to a member function result() on a non-object in D:\wamp\www\ocss\application\core\My_Model.php on line 111
class Report extends MY_Controller{
public function item_ladger()
{
$material = $this->Material_Model->get(); // when i call it here it works fine
$inventory = $this->db->query("CALL inventory($id)")->result_array();
$material = $this->Material_Model->get(); // when i call it here it Generate Fatal error: Call to a member function result() on a non-object in
}
}
what's the reason behind?
EDIT
this is my material model it has table name and all table fields
class Material_Model extends MY_Model
{
const DB_TABLE = 'material';
const DB_TABLE_PK = 'material_id';
public $material_id;
public $material_name;
public $size;
public $rate;
}
this is my MY_Model it has table name and get method to get all result
class MY_Model extends CI_Model {
const DB_TABLE = 'abstract';
const DB_TABLE_PK = 'abstract';
public function get($limit = 500, $offset = 0,$desc=true) {
if ($limit) {
if ($desc)
$query = $this->db->order_by($this::DB_TABLE_PK, 'DESC')->get($this::DB_TABLE, $limit, $offset);
else
$query = $this->db->get($this::DB_TABLE, $limit, $offset);
}
else {
$query = $this->db->get($this::DB_TABLE);
}
$ret_val = array();
$class = get_class($this);
foreach ($query->result() as $row) {
$model = new $class;
$model->populate($row);
$ret_val[$row->{$this::DB_TABLE_PK}] = $model;
}
return $ret_val;
}
Finally i have solved my problem by simply calling mysql query instead store procedure
class Report extends MY_Controller{
public function item_ladger()
{
$material = $this->Material_Model->get(); // when i call it here it works fine
$inventory = $this->db->query("My Query To Database")->result_array();
$material = $this->Material_Model->get(); // now when i call it here there is no error
}
}
but i am confused my that error acure when calling store procedure instead query
class Report extends MY_Controller{
public function item_ladger()
{
$this->load->model("Material_Model"); # loding Model
$inventory = $this->Material_Model->get_data(); # caling Model to do my code
if ($inventory['cup']) { # retrivig data from retund array
echo "I never ate Cup Cakes";
}
}
}
In Model
public function get_data()
{
$query = $this->db->get('cake'); # get data from table
$result = $query->result_array(); # re-Assign as objective array
return $result; # return data
}
Codeigniter SELECT
User::updatemain($set, $where);
This gives Fatal error: Using $this when not in object context
My user class extends from Dbase class and here is user class function:
public static function activate($set, $where) {
return $this->updatemain($set, $where);
here is dbase class (some part of):
private function query($sql = null, $params = null) {
if (!empty($sql)) {
$this->_last_statement = $sql;
if ($this->_db_object == null) {
$this->connect();
}
try {
$statement = $this->_db_object->prepare($sql, $this->_driver_options);
$params = Helper::makeArray($params);
$x = 1;
if (count($params)) {
foreach ($params as $param) {
$statement->bindValue($x, $param);
$x++;
}
}
if (!$statement->execute() || $statement->errorCode() != '0000') {
$error = $statement->errorInfo();
throw new PDOException("Database error {$error[0]} : {$error[2]}, driver error code is {$error[1]}");
exit;
}
//echo $sql;
return $statement;
} catch (PDOException $e) {
echo $this->formatException($e);
exit;
}
}
}
public function updatemain($set, $where) {
return $this->query($sql, $params);
}
this is part of Dbase class
You are calling static method so there is no $this in that context.
If you want to call other static method from given class then use self::method() but if you want to call non-static method you've got problem. First you have to create new object.
When you use static methods, you can't use $this inside
public static function activate($set, $where) {
return self::updatemain($set, $where);
}
Or you have to use singelton design
EDIT
Best solution - rewrite your class to one point access to DB object. And create Model classes to DB access. See my example code below:
core AppCore
<?php
class AppCore
{
public static $config = array();
public static $ormInit = false;
public static function init($config)
{
self::$config = array_merge(self::$config, $config);
}
public static function db($table)
{
// ORM - see http://idiorm.readthedocs.org/en/latest
if (!self::$ormInit) {
ORM::configure(self::$config['db']['connection']);
ORM::configure('username', self::$config['db']['username']);
ORM::configure('password', self::$config['db']['password']);
self::$ormInit = true;
}
return ORM::for_table($table);
}
}
User model
<?php
class UserModel
{
const TABLE = 'user';
public static function findById($u_id)
{
$result = AppCore::db(self::TABLE)->where('u_id', $u_id)->find_one();
return $result ? $result->as_array() : null;
}
}
AppCore init section
AppCore::init(array(
'db' => array(
'connection' => "mysql:dbname={$db};host={$host}",
'username' => $user,
'password' => $pass
),
));
i hope it help make your code better
I'm getting a class not found error but without the name of the class. I got the code from here
but when I try to run it, it gives the following error..
Fatal error: Class '' not found in C:\Program Files\Apache Software Foundation\Apache24\Apache24\htdocs\framework\library\controller.class.php on line 16
and the following is the controller
<?php
class Controller {
protected $_model;
protected $_controller;
protected $_action;
protected $_template;
function __construct($model, $controller, $action) {
$this->_controller = $controller;
$this->_action = $action;
$this->_model = $model;
include 'model.class.php';//other similar posts suggested this but its not working
$this->$model = new $model;
$this->_template = new Template($controller,$action);
}
function set($name,$value) {
$this->_template->set($name,$value);
}
function __destruct() {
$this->_template->render();
}
}
I'm assuming its the model class which is not being found. The model class code is
<?php
class Model extends SQLQuery {
protected $_model;
function __construct() {
$this->connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$this->_model = get_class($this);
$this->_table = strtolower($this->_model)."s";
}
function __destruct() {
}
}
and sqlquery class is
<?php
class SQLQuery {
protected $_dbHandle;
protected $_result;
/** Connects to database **/
function connect($address, $account, $pwd, $name) {
$this->_dbHandle = #mysql_connect($address, $account, $pwd);
if ($this->_dbHandle != 0) {
if (mysql_select_db($name, $this->_dbHandle)) {
return 1;
}
else {
return 0;
}
}
else {
return 0;
}
}
/** Disconnects from database **/
function disconnect() {
if (#mysql_close($this->_dbHandle) != 0) {
return 1;
} else {
return 0;
}
}
function selectAll() {
$query = 'select * from `'.$this->_table.'`';
return $this->query($query);
}
function select($id) {
$query = 'select * from `'.$this->_table.'` where `id` = \''.mysql_real_escape_string($id).'\'';
return $this->query($query, 1);
}
/** Custom SQL Query **/
function query($query, $singleResult = 0) {
$this->_result = mysql_query($query, $this->_dbHandle);
if (preg_match("/select/i",$query)) {
$result = array();
$table = array();
$field = array();
$tempResults = array();
$numOfFields = mysql_num_fields($this->_result);
for ($i = 0; $i < $numOfFields; ++$i) {
array_push($table,mysql_field_table($this->_result, $i));
array_push($field,mysql_field_name($this->_result, $i));
}
while ($row = mysql_fetch_row($this->_result)) {
for ($i = 0;$i < $numOfFields; ++$i) {
$table[$i] = trim(ucfirst($table[$i]),"s");
$tempResults[$table[$i]][$field[$i]] = $row[$i];
}
if ($singleResult == 1) {
mysql_free_result($this->_result);
return $tempResults;
}
array_push($result,$tempResults);
}
mysql_free_result($this->_result);
return($result);
}
}
/** Get number of rows **/
function getNumRows() {
return mysql_num_rows($this->_result);
}
/** Free resources allocated by a query **/
function freeResult() {
mysql_free_result($this->_result);
}
/** Get error string **/
function getError() {
return mysql_error($this->_dbHandle);
}
}
I'm new to PHP and I'm using PHP 5.5.15. I know I should probably switch this to pdo, but i just want to get this working before gettin jiggy with it.
Any help much appreciated
Simple said, you have this function for your controller:
function __construct($model, $controller, $action) {
$this->$model = new $model;
}
You need to give a $model, wich would be the name of a class. You give no name. This is why class "" can not be found.
If we would write this:
$controller = new Controller("mycrazymodel", null, null);
It means:
function __construct($model, $controller, $action) {
//$this->$model = new $model;
$this->$model = new mycrazymodel; //above means this, if $model = "mycrazymodel"
}
So what does this mean for you?
Locate the call of the Controller::__construct method, which typical mean new Controller(...) and make sure, you give the classname as $model parameter.
Take a look at the manual for further information: http://php.net/manual/en/language.namespaces.dynamic.php
I have created a custom model (My_Model) containing all the crud functions. now i want to inherit that general model class in other models.
application/core/My_Model.php
<?php
class My_Model extends CI_Model {
protected $_table;
public function __construct() {
parent::__construct();
$this->load->helper("inflector");
if(!$this->_table){
$this->_table = strtolower(plural(str_replace("_model", "", get_class($this))));
}
}
public function get() {
$args = func_get_args();
if(count($args) > 1 || is_array($args[0])) {
$this->db->where($args[0]);
} else {
$this->db->where("id", $args[0]);
}
return $this->db->get($this->_table)->row();
}
public function get_all() {
$args = func_get_args();
if(count($args) > 1 || is_array($args[0])) {
$this->db->where($args[0]);
} else {
$this->db->where("id", $args[0]);
}
return $this->db->get($this->_table)->result();
}
public function insert($data) {
$success = $this->db->insert($this->_table, $data);
if($success) {
return $this->db->insert_id();
} else {
return FALSE;
}
}
public function update() {
$args = func_get_args();
if(is_array($args[0])) {
$this->db->where($args[0]);
} else {
$this->db->where("id", $args[0]);
}
return $this->db->update($this->_table, $args[1]);
}
public function delete() {
$args = func_get_args();
if(count($args) > 1 || is_array($args[0])) {
$this->db->where($args[0]);
} else {
$this->db->where("id", $args[0]);
}
return $this->db->delete($this->_table);
}
}
?>
application/models/user_model.php
<?php
class User_model extends My_Model { }
?>
application/controllers/users.php
<?php
class Users extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model("user_model");
}
function index() {
if($this->input->post("signup")) {
$data = array(
"username" => $this->input->post("username"),
"email" => $this->input->post("email"),
"password" => $this->input->post("password"),
"fullname" => $this->input->post("fullname")
);
if($this->user_model->insert($data)) {
$this->session->set_flashdata("message", "Success!");
redirect(base_url()."users");
}
}
$this->load->view("user_signup");
}
}
?>
when i load the controller i get an 500 internal server error but
if i uncomment the line in controller -- $this->load->model("user_model");
then the view page loads,...cant figure out whats happening...plz help..
In CI config file 'application/config/config.php' find and set configuration item
$config['subclass_prefix'] = 'My_';
then the CI load_class function will load CI_Model and My_model when calling $ths->load->model('user_model') in your routine;