Codeigniter autocheck db depending on session value - database

I'm trying to force my app to check every time it loads a model or controller depending on which is my session value.
This is actually running, but just when I get throw this model.
class News_model extends CI_Model {
public function __construct()
{
parent::__construct();
if($this->session->dbname=='db1'){
$this->db=$this->load->database('db1', TRUE);
}
else{
$this->db=$this->load->database('db2', TRUE);
}
}
public function get_news($slug = FALSE)
{
if ($slug === FALSE)
{
$query = $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news', array('slug' => $slug));
return $query->row_array();
}
}
But I do not war to include that __construct code to all my models or controllers.
I've tried to add on my autoload.php
$autoload['model'] = array('General');
Where my General code is something like this.
class General extends CI_Model {
function __construct()
{
parent::__construct();
if($this->session->dbname=='db1'){
$this->db=$this->load->database('db1', TRUE);
}
else{
$this->db=$this->load->database('db2', TRUE);
}
}
}
How can I do it?

You can do it by creating a base model which will be extended by your models that require the database check.
I have simplified the checking and loading code. A simple ternary determines the string to use and stores it in the variable $dbname. That variable is used to load the database, i.e. $this->load->database($dbname);.
I don't believe you need the second argument to load::database() which means you don't need to set $this->db explicitly. If I'm wrong, use
$this->db = $this->load->database($dbname, TRUE);
Below is the "base" model. The prefix of the file name is determined in config.php with the setting $config['subclass_prefix'] = 'MY_'; Adjust your base model's file and class name to match the 'subclass_prefix' you use.
/application/core/MY_Model.php
<?php
class MY_Model extends CI_Model
{
public function __construct()
{
parent::__construct();
$dbname = $this->session->dbname == 'db1' ? 'db1' : 'db2';
$this->load->database($dbname);
}
}
Use the above to create other models like so...
class News_model extends MY_Model
{
public function get_news($slug = FALSE)
{
if ($slug === FALSE)
{
$query = $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news', array('slug' => $slug));
return $query->row_array();
}
}

Related

Symfony3 return array from query to json

I have problem, i can't return my posts array to json becouse symfony returns array with entity object?
Its my code:
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$posts = $em->getRepository('AppBundle:Post')->findAll();
return $this->json($posts);
}
I use $this->json is return json data, feature added on sf3.
But this is my result:
[
{},
{},
{}
]
i want to load my posts.
ps. i know, i can use Query builder, and method toArray or something, but is any method to use and DRY? Thx
Because entity can have multiple boundaries, proxy objects and related entities, I personally prefer to explicitly specify what is about to be serialized, like this:
use JsonSerializable;
/**
* #Entity
*/
class SomeEntity implements JsonSerializable
{
/** #Column(length=50) */
private $title;
/** #Column(length=50) */
private $text;
public function jsonSerialize()
{
return array(
'title' => $this->title,
'text' => $this->text,
);
}
}
And then it's as simple as json_encode($someEntityInstance);.
You can use JMSSerializerBundle as well to accomplish your task DRY.
Also, there is an option to write your own serializer to normalize the data.
UPDATE:
If you want multiple representations of a JSON, it can be achieved like this:
use JsonSerializable;
/**
* #Entity
*/
class SomeEntity implements JsonSerializable
{
// ...
protected $isList;
public function toList()
{
$this->isList = TRUE;
return $this;
}
private function jsonSerializeToList()
{
return [ // array representing list... ]
}
public function jsonSerialize()
{
if( $this->isList ) {
$normalized = $this->jsonSerializeToList();
} else {
$normalized = array(
'title' => $this->title,
'text' => $this->text,
);
}
return $normalized;
}
}
And called as json_encode($someEntityInstance->toList());. Any way, this is a bit dirty, so I suggest to be consistent with an idea of the interface.
A best solution is to enable the serializer component in Symfony:
#app/config/config.yml
framework:
serializer: ~
Note: the serializer component is disabled by default, you have to uncomment the config line in app/config/config.yml file.

Declaration of Upload::beforeSave() should be compatible with Model::beforeSave($options = Array) [APP/Model/Upload.php, line 5]

I am being shown the following error on top of my page when using beforeSave method in my Upload model.
Strict (2048): Declaration of Upload::beforeSave() should be
compatible with Model::beforeSave($options = Array)
[APP/Model/Upload.php, line 5]
Could someone point out what I'm doing wrong?
Here is my model:
<?php
App::uses('AppModel', 'Model');
class Upload extends AppModel {
protected function _processFile() {
$file = $this->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK) {
$name = md5($file['name']);
$path = WWW_ROOT . 'files' . DS . $name;
if (is_uploaded_file($file['tmp_name'])
&& move_uploaded_file($file['tmp_name'], $path) ) {
$this->data['Upload']['name'] = $file['name'];
$this->data['Upload']['size'] = $file['size'];
$this->data['Upload']['mime'] = $file['type'];
$this->data['Upload']['path'] = '/files/' . $name;
unset($this->data['Upload']['file']);
return true;
}
}
return false;
}
public function beforeSave() {
if (!parent::beforeSave($options)) {
return false;
}
return $this->_processFile();
}
}
?>
Just change this line
public function beforeSave() {
to this, so you have correct method declaration
public function beforeSave($options = array()) {
The beforeSave() function executes immediately after model data has been successfully validated, but just before the data is saved. This function should also return true if you want the save operation to continue.
This callback is especially handy for any data-massaging logic that needs to happen before your data is stored. If your storage engine needs dates in a specific format, access it at $this->data and modify it.
Below is an example of how beforeSave can be used for date conversion. The code in the example is used for an application with a begindate formatted like YYYY-MM-DD in the database and is displayed like DD-MM-YYYY in the application. Of course this can be changed very easily. Use the code below in the appropriate model.
public function beforeSave($options = array()) {
if (!empty($this->data['Event']['begindate']) &&
!empty($this->data['Event']['enddate'])
) {
$this->data['Event']['begindate'] = $this->dateFormatBeforeSave(
$this->data['Event']['begindate']
);
$this->data['Event']['enddate'] = $this->dateFormatBeforeSave(
$this->data['Event']['enddate']
);
}
return true;
}
public function dateFormatBeforeSave($dateString) {
return date('Y-m-d', strtotime($dateString));
}
Make sure that beforeSave() returns true, or your save is going to fail.

Zend framework 2 model for database, separate model for each table?

I looked through the manual of Zend Framework 2 about creating model to managing operations on table. Is the class with method exchangeArray() is necessary? It's only copy data :/ Can i create one model to manage a few tables?
I created two classes:
namespace Application\Model;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Adapter\AdapterAwareInterface;
abstract class AbstractAdapterAware implements AdapterAwareInterface
{
protected $db;
public function setDbAdapter(Adapter $adapter)
{
$this->db = $adapter;
}
}
and:
namespace Application\Model;
class ExampleModel extends AbstractAdapterAware
{
public function fetchAllStudents()
{
$result = $this->db->query('select * from Student')->execute();
return $result;
}
}
I also add entries in Module.php:
'initializers' => [
'Application\Model\Initializer' => function($instance, \Zend\ServiceManager\ServiceLocatorInterface $serviceLocator){
if ($instance instanceof AdapterAwareInterface)
{
$instance->setDbAdapter($serviceLocator->get('Zend\Db\Adapter\Adapter'));
}
}
],
'invokables' => [
'ExampleModel' => 'Application\Model\ExampleModel'
],
I execute methods from model by:
$this->getServiceLocator()->get('ExampleModel')->fetchAllStudents();
You should do 2 things with your code. First, implement AdapterAwareInterface properly. Second, create an initializer which injects the adapter into your model. Consider the code below:
...
'initializers' => [
function($instance, ServiceLocatorInterface $serviceLocator){
if ($instance instanceof AdapterAwareInterface) {
$instance->setDbAdapter($serviceLocator->get('Zend\Db\Adapter\Adapter'));
}
}
]
...
abstract class AbstractModel implements AdapterAwareInterface
{
protected $db;
public function setDbAdapter(Adapter $adapter)
{
$this->db = adapter;
}
}
...
'invokables' => [
'ExampleModel' => 'Application\Model\ExampleModel'
]
As you can see from above, after all, you don't need a factory for each your model. You can either register invokables or create an Abstract Factory to instantiate your models. See an example below:
...
'abstract_factories' => [
'Application\Model\AbstractFactory'
]
...
class AbstractFactory implements AbstractFactoryInterface
{
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
return class_exists('Application\Model\'.$requestedName);
}
public function createServiceWithName(\Zend\ServiceManager\ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
$class = 'Application\Model\'.$requestedName();
return new $class
}
}
Hope this helps

A better way for using DB connection [PDO] using an class and further using it in other class?

I'm searching for a better PDO db connection which I could use in the different classes I have. For example my current code is like this:
core.php
//Connecting to Database
try {
$db = new PDO("mysql:host=localhost;dbname=mydb", "project", "project123");
}
catch(PDOException $e) {
echo $e->getMessage();
}
class Core {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
function redirectTo($page,$mode = 'response',$message = '') {
if($message != '') {
header('Location: '.SITEURL.'/'.$page.'?'.$mode.'='.urlencode($message));
} else {
header('Location: '.SITEURL.'/'.$page);
}
exit();
}
}
And apart from this I have 2 more class: wall.php and ticker.php
class Wall {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
function addComment($uid, $fid, $comment) {
$time = time();
$ip = $_SERVER['REMOTE_ADDR'];
$query = $this->db->prepare('INSERT INTO wall_comments (comment, uid_fk, msg_id_fk, ip, created) VALUES (:comment, :uid, :fid, :ip, :time)');
$query->execute(array(':comment' => $comment, ':uid' => $uid, ':fid' => $fid, ':ip' => $ip, ':time' => $time));
$nofity_msg = "User commented on the post";
$setTicker = Ticker::addTicker($uid,$nofity_msg,'comment');
if($setTicker) {
Core::redirectTo('wall/view-'.$fid.'/','error','Oops, You have already posted it!');
} else {
Core::redirectTo('wall/view-'.$fid.'/','error','Oops, Error Occured');
}
}
}
and ticker.php is:
class Ticker {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
function addTicker($uid,$msg,$type) {
$time = time();
$query = $this->db->prepare('INSERT INTO tickers (uid_fk, message, type, created) VALUES (:uid, :message, :type, :time)');
try {
$query->execute(array(':uid' => $uid, ':message' => $msg, ':type' => $type, ':time' => $time));
return $this->db->lastInsertId();
}
catch(PDOException $e) {
return 0;
}
}
}
Now my problem is that I need to call for the function addComment() and inside that function there is a further call for the function addTicker() present in the class Ticker. This is causing a Db connection problem as there is already an db instance created in the previous class or so.. I can't figure out how to sort this out.
This is the code I'm using in the main index file:
$core = new Core($db);
$ticker = new Ticker($db);
$wall = new Wall($db);
$wall->addComment($uid, $fid, $add_comment); // This statement is not working.. :(
My intention is to have a common main DB connection and further use that connection in other classes. Is there any better way to do it..?
there is already an db instance created in the previous class
this is actually single instance, but copied into 2 variables.
This is causing a Db connection problem
Can you please be a bit more certain about such a problem? What particular problem you have?

How to display session variables in cakePHP

I have a controller class below which adds a student in to session.
class StudentsController extends AppController
{
var $name="Student";
function addstudent()
{
//$id=$_REQUEST['id'];
//$this->Session->write('id', $id);
static $count=0;
if (!empty($this->data)) {
$students = $this->Session->read('Student');
if (!$students) {
$students = array();
}
$students[] = $this->data['Student'];/* data */
$this->Session->write('Student', $students);
$this->Session->write('student_count',$count);
$this->redirect(array('controller'=>'students','action' => 'addstudent'));
}
}
}
my question is how to display all the added students in the view page.please explain me with syntax
Add the Session helper to your view. The code to access the student_count variable would be
$session->read('student_count');
The general syntax is
$session->read('var_name');
$student_list = $this->Session->write('Student', $students);
$student_count = $this->Session->write('student_count',$count);
$this->set('$student_list',student_list);
$this->set('$student_count',student_count);
use the student_list and student_count in view page .

Resources