RedBean ORM and Codeigniter, how to make Fuse recognize models loaded from CI default models path? - codeigniter

Codeigniter has its own Models path, where models extend from CI_Model. I'm using RedBean has a library in Codeigniter, loading it on a controller. After loading Rb, I try to use CI Loader to load a model that extends redbean_simplemodel (wish works, there's no error), but the events / methods inside the model have no effect when they're called on bean.
For example,
APPPATH/application/libraries/rb.php
class Rb {
function __construct()
{
// Include database configuration
include(APPPATH.'/config/database.php');
// Get Redbean
include(APPPATH.'/third_party/rb/rb.php');
// Database data
$host = $db[$active_group]['hostname'];
$user = $db[$active_group]['username'];
$pass = $db[$active_group]['password'];
$db = $db[$active_group]['database'];
// Setup DB connection
R::setup("mysql:host=$host;dbname=$db", $user, $pass);
} //end __contruct()
} //end Rb
And then on
APPPATH/application/models/model_song.php
class Model_song extends RedBean_SimpleModel {
public function store() {
if ( $this->title != 'test' ) {
throw new Exception("Illegal title, not equal «test»!");
}
}
}
while on
APPPATH/application/controllers/welcome.php
class Welcome extends CI_Controller {
public function index()
{
$this->load->library('rb');
$this->load->model('model_song');
$song = R::dispense('song');
$song->title = 'bluuuh';
$song->track = 4;
$id = R::store($song);
echo $id;
}
}
My question is, how to make RedBean (FUSE http://redbeanphp.com/#/Fuse) work on Codeigniter ?
Thanks for looking!
----- FOUND SOLUTION!
Actually, it's working! I was trying to place code under my model, method store(). That wont work! I tryed to place a new method called update() and it does work! Check the example below:
class Model_song extends RedBean_SimpleModel {
public function update() {
if ( $this->title != 'test' ) {
throw new Exception("Illegal title!");
}
}
}
The solution is the following:
"Assuming that you've already installed RedBean on Codeigniter"
1) Load the library for «redbean»
2) Using ci_loader, load the desired model (the model must extend redbean_simplemodel)
Thanks for looking! I hope this helps other people too.

The solution is the following:
"Assuming that you've already installed RedBean on Codeigniter"
Load the library for «redbean»
Using ci_loader, load the desired model (the model must extend redbean_simplemodel)

Related

Calling same eloquent statement in several controllers

I have an eloquent statement like this:
$constraint = function ($query) {
$query->where('session', Session::getId());
};
$selectedImages = ImageSession::with(['folder' => $constraint])
->whereHas('folder', $constraint)
->where('type', 'single')
->get();
Which I need to call in several controllers.
How is the best way to do it without putting this code every time?
Should I put this code in the Model? but how I put the ImageSession::with if it is inside the same model that has ImageSession class?
In the controller do I have to write...
$imageSession_table = new ImageSession;
$selectedImages = $imageSession_table->getSelectedImages();
Well there are several solutions to this, but one rule that I have learned is whenever you are doing copy paste in the same file it means you need to create a function to encapsulate that code.
The same applies when you are copying and pasting the same code over classes/controllers it means you need to create a class that will have a method, that will encapsulate that code.
Now you could in fact change your model and this depends on your application and what kind of level of abstraction you have.
Some people tend to leave the models as pure as possible and then use transformers, repositories, classes whatever you want to call it. So the flow of communication is something like this:
Models -> (transformers, repositories, classes) -> Controllers or other classes
If that's the case just create a ImageSessionRepository and in there have your method to get the selected images:
<?php namespace Your\Namespace;
use ImageSession;
use Session;
class ImageSessionRepository
{
protected $imageSession;
public function __construct(ImageSession $imageSession)
{
$this->imageSession = $imageSession;
}
public function getSelectedImages($sessionId = false){
if(!$sessionId){
$sessionId = Session::getId()
}
$constraint = function ($query) use ($sessionId){
$query->where('session', $sessionId);
};
$selectedImages = ImageSession::with(['folder' => $constraint])
->whereHas('folder', $constraint)
->where('type', 'single')
->get();
return $selectedImages;
}
}
Then on your controller you just inject it:
<?php namespace APP\Http\Controllers;
use Your\Namespace\ImageSessionRepository;
class YourController extends Controller
{
/**
* #var ImageSessionRepository
*/
protected $imageSessionRepository;
public function __construct(ImageSessionRepository $imageSessionRepository)
{
$this->imageSessionRepository = $imageSessionRepository;
}
public function getImages()
{
$selectedImages = $this->imageSessionRepository->getSelectedImages();
//or if you want to pass a Session id
$selectedImages = $this->imageSessionRepository->getSelectedImages($sessionID = 1234);
//return the selected images as json
return response()->json($selectedImages);
}
}
Another option is adding that code directly into your Model, using scopes, more info here
So on your ImageSession Model just add this function:
public function scopeSessionFolder($query, $session)
{
$constraint = function ($constraintQuery) use ($sessionId){
$query->where('session', $sessionId);
};
return $query->with(['folder' => $constraint])
->whereHas('folder', $constraint);
}
And on your controller just do this:
$selectedImages = ImageSession::sessionFolder(Session::getId())
->where('type', 'single')
->get();
Or you can include everything in your scope if that's your case
public function scopeSessionFolder($query, $session)
{
$constraint = function ($constraintQuery) use ($sessionId){
$query->where('session', $sessionId);
};
return $query->with(['folder' => $constraint])
->whereHas('folder', $constraint);
->where('type', 'single');
}
And then again on your controller you will have something like this:
$selectedImages = ImageSession::sessionFolder(Session::getId())
->get();
Just a side note I haven't tested this code, so if you just copy and paste it it's possible that you find some errors.

Symfony 1.4 doctrine model object data retrieve issue

In my symfony 1.4 application i'm using doctrine data models.I'm new to symfony and doctrine.I generated doctrine models from command-line after defining database table information in the schema.yml file.Those generated successfully.Then i created a custom function inside Table.class.php file.Following is that.
class Table extends BaseTable
{
public function getuname()
{
$user=new Table();
$uname=$user->getUsername();
return $uname;
}
}
I want to know how to call this inside the controller ? I called it normal MVC application's way.But i don't know whether it's correct in symfony.In symfony 1.4 manual also i couldn't find a proper way to do this.
This is my controller.
class loginActions extends sfActions
{
public function executeIndex(sfWebRequest $request)
{
$this->userdata = User::getuname();
}
}
Then i tried to print this inside view.
<?php
echo $userdata;
?>
But view is showing an empty page.
Update with exception details--------------------------------
stack trace
at ()
in SF_SYMFONY_LIB_DIR\plugins\sfDoctrinePlugin\lib\vendor\doctrine\Doctrine\Connection.php line 1082 ...
$message .= sprintf('. Failing Query: "%s"', $query);
}
$exc = new $name($message, (int) $e->getCode());
if ( ! isset($e->errorInfo) || ! is_array($e->errorInfo)) {
$e->errorInfo = array(null, null, null, null);
}
When using Doctrine you retrieve objects from the database using the ...Table classes (in your case it will be a TableTable class. You can use its' methods to fetch objects from DB (e.g. find($id)) and then access them. So in your case your classes should something like this:
class Table extends BaseTable
{
public function getuname()
{
return $this->getUsername();
}
}
Now it effectively becomes just an alias of getUsername().
Then in your action:
class loginActions extends sfActions
{
public function executeIndex(sfWebRequest $request)
{
$user = Doctrine_Core::getTable('Table')->find(123);
$this->userdata = $user->getuname();
}
}
This will print the username in your template (assuming of course that you have a user with id 123).

Simple AJAX / JSON response with CakePHP

I'm new to cakePHP. Needless to say I don't know where to start reading. Read several pages about AJAX and JSON responses and all I could understand is that somehow I need to use Router::parseExtensions() and RequestHandlerComponent, but none had a sample code I could read.
What I need is to call function MyController::listAll() and return a Model::find('all') in JSON format so I can use it with JS.
Do I need a View for this?
In what folder should that view go?
What extension should it have?
Where do I put the Router::parseExtension() and RequestHandlerComponent?
// Controller
public function listAll() {
$myModel = $this->MyModel->find('all');
if($this->request->is('ajax') {
$this->layout=null;
// What else?
}
}
I don't know what you read but I guess it was not the official documentation. The official documentation contains examples how to do it.
class PostsController extends AppController {
public $components = array('RequestHandler');
public function index() {
// some code that created $posts and $comments
$this->set(compact('posts', 'comments'));
$this->set('_serialize', array('posts', 'comments'));
}
}
If the action is called with the .json extension you get json back, if its called with .xml you'll get xml back.
If you want or need to you can still create view files. Its as well explained on that page.
// Controller code
class PostsController extends AppController {
public function index() {
$this->set(compact('posts', 'comments'));
}
}
// View code - app/View/Posts/json/index.ctp
foreach ($posts as &$post) {
unset($post['Post']['generated_html']);
}
echo json_encode(compact('posts', 'comments'));
// Controller
public function listAll() {
$myModel = $this->MyModel->find('all');
if($this->request->is('ajax') {
$this->layout=null;
// What else?
echo json_encode($myModel);
exit;
// What else?
}
}
You must use exit after the echo and you are already using layout null so that is OK.
You do not have to use View for this, and it is your wish to work with components. Well all you can do from controller itself and there is nothing wrong with it!
Iinjoy
In Cakephp 3.5 you can send json response as below:
//in the controller
public function XYZ() {
$this->viewBuilder()->setlayout(null);
$this->autoRender = false;
$taskData = $this->_getTaskData();
$data = $this->XYZ->getAllEventsById( $taskData['tenderId']);
$this->response->type('json');
$this->response->body(json_encode($data));
return $this->response;
}
Try this:
public function listAll(){
$this->autoRender=false;
$output = $this->MyModel->find('all')->toArray();
$this->response = $this->response->withType('json');
$json = json_encode($output);
$this->response = $this->response->withStringBody($json);
}

codeigniter best way to create controller for editing a db row

Im new to codeigniter and im developing my first web application with it and want to make sure im doing best practices the 1st time so i dont have to go back to make corrections down the road. with that said, here is what im doing.
I want to edit a note in the DB, then after the record has been updated redirect to a different page.
my model is coded correctly so im not worried there, but the controller looks like this (and this is probably not correct:
public function edit($id) {
$this->load->model('Notes_model');
if (isset($_POST["edit"]))
{
$data['data'] = $this->Notes_model->edit($id);
$url = "/Notes/view/" . $id;
redirect($url);
}
$data['notes'] = $this->Notes_model->viewNotes($id);
$this->load->view('templates/header');
$this->load->view('notes/edit', $data);
$this->load->view('templates/footer');
}
hopefull this makes sense, basically what I'm wanting to do here is:
1.) Show the edit note page
2.) if i edited that page by hitting submit
a.) update the db
b.) redirect to a different page.
does this look pretty good or should i make some better changes?
Although your controller code is fine but one thing you have to take care that you should load model in the constructor of your controller so you don't have to include the model in each function same recommendations for the libraries, helpers this is the best practice
class myclass extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('Notes_model');
$this->load->helper(form);
}
public function myfunction(){
}
}
Here is the starting tutorial with MVC standards advanced-codeigniter-techniques-and-tricks
<?php
class Home extends CI_Controller
{
function __construct() {
parent::__construct();
$this->m_auth->notLogin();
$this->load->library('form_validation');
$this->load->library('ajax_pagination');
$this->load->library('dateconverter');
$this->load->helper('template');
$this->load->helper('check');
$this->load->model('mymodels/crud_model');
$this->lang->load('personal', $this->m_auth->get_language());
$this->lang->load('global', $this->m_auth->get_language());
}
function index()
{
$this->get_recs();
}
function get_recs()
{
//get for view or first page to be showed
}
/**
* Register New User
*/
function updateRecords()
{
$this->form_validation->set_rules('ministery','<span class="req">(Ministry)</span>','trim|required');
$this->form_validation->set_rules('directorate','<span class="req">(Directorate)</span>','trim|required');
if($this->form_validation->run()==FALSE)
{
header_tpl($this->m_auth->get_language(),'a');
banner_tpl($this->m_auth->get_language(),'a');
left_tpl($this->m_auth->get_language(),'a');
$content = $this->load->view('personal/edit_personal', $this->POST,true);
content_tpl($content);
footer_tpl();
}
else
{
$form_data = array(
'ministry' => $this->input->post('ministery'),
'directorate' => $this->input->post('directorate'),
'job_province' => $this->input->post('job_province'),
'job_district' => $this->input->post('job_district'),
'first_name' => $this->input->post('fname'),
'last_name' => $this->input->post('lname')
);
if($this->crud_model->update_recs('ast_emp_property',$form_data)==TRUE)
{
$this->session->set_flashdata("msg","<span class='m_success'>".$this->lang->line('global_insert_success')."</span>");
redirect('/home/success_reg/'.$id.'','refresh');
}
else
{
$this->session->set_flashdata("msg","<span class='m_error'>".$this->lang->line('global_insert_error')."</span>");
redirect('home','refresh');
}
}
}
}
?>

CodeIgniter: loading multiple models in the same controller

I searched the whole Internet and either there is no one mentioning my problem, or I'm stupid, or maybe it's just a bad day for coding.
What's the situation:
controller "source"
model "source"
model "login"
The "login" model is loaded from autoload.php, then in each controller's constructor I have $this->login->check(), which is checking if the user is logged in (obviously). Then in some of the methods I'm using the "source" model to connect to the database.
I tried loading both of the models from the autoload array, I also tried to load them in the way described here, but it's obviously for an old CI version (the thread is from 2008) and I tried all the possible ways I had in my mind.
Anyway, the result is this:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Source::$login
Filename: controllers/source.php
Line Number: 10
Fatal error: Call to a member function check() on a non-object in ...\application\controllers\source.php on line 10
Any ideas what I'm missing or how to fix it...? I'm stuck for hours and I don't have any ideas what I could do...
Edit 1: here is the code from the "source" controller:
class Source extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('login');
$this->login->check();
}
function index() {
// Pagination config, getting records from DB
$this->load->view('templates/layout', $data);
}
function add() {
$this->load->model('source', '', true);
$btn = $this->input->post('btn');
if(isset($btn)) {
// More form validation
if($this->form_validation->run() == TRUE) {
if($btn == "Add") {
// here I am supposed to use the source model...
}
}
}
$data['page'] = 'source_add';
$this->load->view('templates/layout', $data);
}
}
?>
Edit 2: login.php:
<?php
class Login extends CI_Model {
function __construct() {
parent::__construct();
}
function authenticate($username, $password) {
// the login script comes here
}
function logged() {
if($this->session->userdata('logged') == true) {
return true;
} else return false;
}
function check() {
if(!$this->logged()) {
redirect('/authentication');
}
}
}
?>
Conventionally, the classname of Models should end with _model, so it not collides with controllers with the same name, so try changing
class Login extends CI_Model {
to
class Login_model extends CI_Model {
I resolved this issue by utilizing the hooks and turned the login process into a controller, thereby being able to access user information and setting access levels.
First I added the following to the hooks.php file in the config folder
$hook['post_controller_constructor'][] = array('function' => 'check_login','filename' => 'authority.php','filepath' => 'hooks');
Then I have the following functions in a hook file called authority.php
[EDIT]Having reviewed this I am going to change it to a pre_controller_constructor and see if I can remove what seems to be a double page flash on initial construct.[/EDIT]
function check_login(){
$CI =& get_instance();
$is_logged_in = $CI->session->userdata('is_logged_in');
if(!$is_logged_in){
$unauth_pages = array(your unauthorized pages go here);
if(!in_array($CI->router->class,$unauth_pages)){
$CI->session->set_userdata('before_login_url',current_url());
redirect('login');
}
}
}
function check_authority(){
$CI =& get_instance();
if($CI->session->userdata('usergroupID') == 'SUPADMIN'){return;}
$page = $CI->router->class ;
$method = $CI->router->method;
$method = ($method=='index')?'':$method;
$unauth_pages = array(your unauthorized pages go here);
if(in_array($page,$unauth_pages))return;
$user_group = $CI->session->userdata('usergroupID');
$CI->load->model('user_model');
if($user_group == 'ADMIN' || $user_group == 'USER'){
if($CI->session->userdata('timezone') == ''){
date_default_timezone_set('Canada/Pacific');
} else {
date_default_timezone_set($CI->session->userdata('timezone'));
}
}
if( !$CI->user_model->authorized_content($CI->session->userdata('usergroupID'),$page, $method)){
redirect('unauthorized');
}
}
With the above I dont have to worry about checking on each page but instead utilize the ci framework to do the checking for me.. if its not in the unauth page array then it is a page that requires authorization checking.
Hope this works for you.

Resources