I have this controller and model:
class MyModel extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function insert($data_array)
{
$this->db->insert('table', $data_array);
if($this->db->affected_rows() == 1) {
return true;
}
return false;
}
}
class Panel extends CI_Controller
{
public function submitPrimer()
{
// evaluate data
$this->load->library('form_validation');
$this->load->model('MyModel', 'mymodel');
// validate, set_rules....
$data = array(
'column1' => $value1;
// .....
);
if($this->mymodel->insert($data)) {
echo "inserted";
}
}
}
Is there any kind of $this->db->show_warnings() in CI. In mysql console there is 'show warnings' command which says for example if you have datatype: float and you insert like this: insert into table (attribute_float) values(''). The proper way would be insert into table (attribute_float) values(NULL).
I also am wondering if 'insert' should go to models. I always assumed only 'select/get' data would go.
As much as I'm aware, and from user guide, I don't think that Codeigniter has such a function, for such validation use form_validation library, it's pretty good.
As for insert/edit/delete, they usually go to the model, but it depends on you.
Related
I want to restrict or give access to all of my fuction inside a controller by checking some condition in cakephp 3.6.
Suppose I have add(), edit(), view($id) function in my PostController.php . Now I have an input field where user will put an unique id. If this id is present in the database then I want to give access to those function. Oterwise it should show a message to the user.
I am new in cakePHP, so I don't have much idea about cakePHP.
I have tried using beforeFilter. But it is not working.
Here is the code that I have tried. Right now I am not checking with database. Just checking if code is given in input field or not.
public function beforeFilter(Event $event)
{
if(!empty($event->subject()->request->data)){
return true;
}
else{
return false;
}
}
I know maybe those are not proper. But I am not getting proper idea even not proper documentation also.
Here is my controller code structure.
use App\Controller\AppController;
use Cake\Event\Event;
class CodesController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
public function beforeFilter(Event $event)
{
if(!empty($event->subject()->request->data)){
return true;
}
else{
return false;
}
}
public function add()
{
//code will be here
}
public function view($id)
{
//code will be here
}
}
Instead of return true from your beforeFilter, use:
$this->Auth->allow(['add', 'edit', 'view']);
No need to do anything in the false case.
Alternately, if those are your only functions, you can simplify to:
$this->Auth->allow();
More details in the manual.
In controller I am sending data like that :
$data=array[
'table'=>'ci',
'where'=>'',
'val'=>['name'=>$name,
'pass'=>$pass,
'mobile'=>$mobile,
'date'=>$date,
'status'=>$status
]
];
$this->load->model('show_model');
$this->show_model->insert_data($data);
In the model code I have:
<?php
class show_model extends CI_model{
public function insert_data($data){
}
}
?>
I want to create a function to data in ci table what is the method to get the data from the controller and how can i make the funcyion for insert for what i am sending the data.
I think you are trying to perform insert operation but you couldn't figure it out. Lets take it step by step. Codeigniter has a database library which comes with installation. You can load that library in config->autoload.php and provide database credentials in config->database.php. All set!
Once you have loaded database library you can use bunch of database function. E.g
For Insertion
$this->db->insert('table_name',data);
// Your data can be array of the data you want to insert
Let's say you want to send data from your controller to your Model to save it to db you can do something like this
Class Controller_Name extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('your_model');
}
public function index() {
$data=array(
'username' => 'Your Name',
'email' => 'Your Email',
'password' => 'Your Password'
);
// Send it to DB
$this->your_model->save_data($data);
// Show success
echo 'Data Saved';
}
}
Now in your Model you will have the function save data like this
Class Your_model extends CI_Model {
public function __construct(){
parent::__construct();
}
public function save_data($data){
// Assuming the table name is users
$this->db->insert('users',$data);
}
}
You can do a lot of modifications and enhancements, there is a lot of learning ahead but this is a fair start.
Try
public function insert($data) {
if($this->db->insert('table_name', $data)) {
//Success
}
}
Ensure you are connected to your database from database.php in application/config folder
Hope it helps
So I have Model, View and Controller, my code works but i have no one to educate me if I do work with it properly.
I won't copy paste the whole code, so therefor I've drawed how it works:
THE PICTURE: MVC
The part of code:
class Site {
protected $config;
function __construct() {
$this->config = include("resources/config.php");
}
private function connect() { /*database connection*/ }
public function getData($var) {
/* connecting, $var = amout of rows, and storing the data in array() */
}
}
class SiteView {
private $data;
function __construct(Site $data) {
$this->model = $data;
}
public function output() {
if(!empty($this->model->data)) { /* displays the data */ }
}
public function render($template) {
return include("$template");
}
}
class SiteController {
public function __construct(Site $respond) {
$this->model = $respond;
}
public function condition() {
$view = new SiteView($this->model);
$view->render("header.php");
if(!isset($_GET['action'])) {
$view->render("body.php");
} else if($_GET['action'] === "report" AND isset($_GET['id'])) {
$view->render("report_body.php");
} else if ...
}
So the model and view is used in templates, and I'm not sure if it is a good thing or bad. Thanks for any kind of help or showing me the way.
The MVC or Model, View and Controller approach is Model is for data which used by user, Controller is the backend logic and View is the output in HTML or the User Interface (UI).
Normally every request come to the controller first. Controller is connected with the Model and View. Controller collect the data according to the request from Model and send the data to the View for show. View can not able to connect with model.
For more details see this link, Click Here
I am working on a project on Laravel, and I have developed my own version of User. I know that Laravel comes with it is own implementation, but just for the sake of the argument, let's forget that.
I am trying to learn how to test in Laravel, and I encountered the following problem:
Part of the controller
<?php
class UsersController extends BaseController {
protected $user;
public function __construct(User $user) {
$this->user = $user;
}
public function login() {
// Input, Validation, blah, blah blah
....
// Find user
$users = $this->user->where('email', '=', $email);
if ($users->count() == 0) {
// Do something
} else {
// Do something else different
}
// Lot more stuff...
}
}
Now comes testing. As you see I put the dependency of Eloquent through the constructor so I can mock it. The test are as follow:
<?php
class UsertTest extends TestCase {
public function __construct() {
$this->userMock = Mockery::mock('Eloquent', 'User');
}
public function tearDown() {
Mockery::close();
}
public function testLogin() {
// Unimportant
$data = ...
$this->userMock
->shouldReceive('where')
->once()
->andReturn('foo');
$this->app->instance('User', $this->userMock);
// Send the data
$this->post('/login', $data);
When I run the tests, I get this error
PHP Fatal error: Call to a member function count() on a non-object
So it seems that the mock is working, in the sense that the Database is not being hit, but now I am with the problem that I need to mock as well the value returned by the call.
How should I go about it?
I'm using CakePhp 2.2 and I have this simple controller, named ProvidersController:
<?php
class ProvidersController extends AppController {
public $components = array('Session', 'Social');
public $layout = false;
public function facebook(){
$this->Social->auth('facebook', 'success', 'error');
$this->render(false);
}
public function google(){
$this->Social->auth('google', 'success', 'error');
$this->render(false);
}
private function success(){
}
private function error(){
}
}
?>
and this Component, named SocialComponent:
<?php
class SocialComponent extends Component {
public function auth($provider, $success, $error){
}
}
?>
as you can see I have created success() and error() methods inside the controller. Now I pass these names and I would like to call them back from the component.
I only pass the name of the callback, how to call them from the component?
Thank you!
Have a look at the source code of the SecurityComponent in CakePHP, it has an identical situation with its blackHoleCallback.
They use a helper function SecurityComponent::_callback() which uses PHP's call_user_func_array()
protected function _callback(Controller $controller, $method, $params = array()) {
if (is_callable(array($controller, $method))) {
return call_user_func_array(array(&$controller, $method), empty($params) ? null : $params);
} else {
return null;
}
}
You can use the same pattern to pass callbacks into your component.
The point of a component is re-usability across many controllers - if you're trying to make it access a specific controller function, you should probably just be using controller methods, not a component.
BUT - you can always just do your logic in the component and pass back data (upon success or error), then check the results in the controller, and access whichever method you'd like based on those results.
Since your 'success' or 'error' logic is in the controller, I assume you don't want it in the component... ie it's different per use of the component. In that case, all you really want the component to do is do the logic and let you know how it went (return data).
//Controller
//..
public function facebook(){
$results = $this->Social->auth('facebook', 'success', 'error');
if($results['error']) $this->Social->error();
$this->render(false);
}
private function success(){ }
private function error(){ }
//...
//Component
//...
public function auth($provider, $success, $error){
$results = array();
//do something
$results['error'] = true;
return $results;
}
//...