Problem loading models with modules in Zend Framework - php

I have a folder structure like this and I'm trying to load the News model inside my controller:
<?php
/**
* Login
*/
class Admin_NewsController extends Zend_Controller_Action {
public function preDispatch() {
$layout = Zend_Layout::getMvcInstance();
$layout->setLayout('admin');
}
public function init() {
$this->db = new Application_Admin_Model_DbTable_News();
}
public function indexAction() {
}
public function addAction() {
//$this->getHelper('viewRenderer')->setNoRender();
// Calls the Request object
$request = $this->getRequest();
if ($request->isPost()) {
// Retrieves form data
$data = array(
"new_title" => $request->getParam('txtTitle'),
"new_text" => htmlentities($request->getParam('txtNews')),
"new_image" => $request->getParam('upName'),
"new_published" => 1
);
// Inserts in the database
if ($this->db->addNews($data)) {
$this->view->output = 1;
} else {
$this->view->output = 0;
}
} else {
$this->view->output = 0;
}
$this->_helper->layout->disableLayout();
}
}
And my model:
<?php
class Application_Admin_Model_DbTable_News extends Zend_Db_Table_Abstract
{
protected $_name = 'news';
public function addNews($data) {
$this->insert($data);
}
}
Althoug I'm getting this error:

Since your News class belongs to the module, its name should be Admin_Model_DbTable_News, without Application_ prefix.
See more on autoloading within modules at http://framework.zend.com/manual/en/zend.loader.autoloader-resource.html#zend.loader.autoloader-resource.module

Related

How to call Base Controllers Method in Codeigniter?

I Have Defined MY_ Controller in my core folder.
Then i have two controllers:
Admin_Controller
Customer_Controller
Now i want to put a query into my Customer_Controller whose result i can access all the controller which extends to Customer_Controllers.
I have put this code in Customer_Controller
public function get_users()
{
$id = $this->session->userdata('id');
$this->db->select('*');
$this->db->join('tenant','tenant.id = sites.tenant_id');
$this->db->where('tenant.id',$id);
$this->db->from('sites');
$query = $this->db->get();
$result = $query->result();
$sitedata = json_decode(json_encode($result));
$this->session->set_userdata($sitedata);
}
Now when i have a child class something like this
<?php
class User extends Customer_Controller
{
public function__construct()
{
parent::__construct();
}
public function index()
{
//Get Results from Customer_Controller
}
}
how do this?
you can follow this:
class Customer_Controller extends My_Controller
{
public function customer()
{
return 'costomers';
}
}
then
class User extends Customer_Controller
{
//call the function from Customer_Controller
$this->customer();
}
Let me give you a suggestion. Instead of creating a controller and extending the same, why don't you create a library class.
And then load your library inside the controller you want.
for example here is your library class file.
<?php
class users{
private $session;
public function __construct(){
$CI =& get_instance();
$this->session=$CI->session;
}
public function get_users()
{
// do the code and return the
}
}
AND in your controller
<?php
class User extends CI_Controller
{
public function__construct()
{
parent::__construct();
}
public function index()
{
$this->load->library('users');
$users = new users();
$userinfo = users->get_users();
//Results from library
}
}
You Try get_instance() like this in you User Controller
public function get_users()
{
$id = $this->session->userdata('id');
$this->db->select('*');
$this->db->join('tenant','tenant.id = sites.tenant_id');
$this->db->where('tenant.id',$id);
$this->db->from('sites');
$query = $this->db->get();
$result = $query->result();
$sitedata = json_decode(json_encode($result));
$this->session->set_userdata($sitedata);
return $result;
}
class User extends CI_controller
{
public function__construct()
{
parent::__construct();
}
public function index()
{
$CI=&get_instance();
$result=$CI->get_users();
foreach($result as $row)
{
echo $row->id;//here add you table field name for id
}
}
}
Codeigniter is MVC framework.
So You will put get_users in model part.
example: you must making custom_model.php in models folder.
<?php
class custom_model extends CI_Model {
function __construct()
{
parent::__construct();
}
public function get_users($id)
{
$this->db->select('*');
$this->db->join('tenant','tenant.id = sites.tenant_id');
$this->db->where('tenant.id',$id);
$this->db->from('sites');
$query = $this->db->get();
$result = $query->result();
return $result;
}
}
?>
next step: you are remake custom_controller.
public function get_users()
{
$id = $this->session->userdata('id');
$this->load->model('custom_model');
$result=$this->cutom_model->get_users($id);
$sitedata = json_decode(json_encode($result));
$this->session->set_userdata($sitedata);
}
and next step:
class User extends Customer_Controller
{
public function__construct()
{
parent::__construct();
}
public function index()
{
//
}
public function get_users(){
parent::get_users();
}

UnitTest a PHP CodeIgniter Controller that calls a model

I'm testing my CodeIgniter project with PHPUnit Testing framework (CITest.php). When the function test_model(), calls the model directly to get the details of an user, it works perfectly. But when I do the same via a controller by calling the function test_controller(), it does not output anything (When I debugged, the model itself doesn't gets called). I even verfied if the post data is passed correctly by creating a function test_post_data(). Am I missing something?
I could only find online resources to test the mdoel directly or a controller separately. But I couldn't find any useful link which calls a controller that triggers the model.
CITest.php
class CITest extends PHPUnit_Framework_TestCase
{
private $CI;
public function setUp()
{
$this->CI = &get_instance();
$this->CI->load->model('Test_model');
$this->model = $this->CI->My_model; // load the model
$this->auth = new Test_controller; // load the controller
}
public test_model() {
$user_id = 6;
print_r($this->model->getUserData($user_id));
}
public test_post_data() {
$_POST['useR_id'] = 22;
print_r($this->model->check_post_data());
}
public test_controller() {
$_POST['useR_id'] = 22;
print_r($this->model->get_user_data());
}
}
Test_controller.php
class Test_controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Test_model');
}
public function check_post_data() {
return $this->input->post();
}
public function get_user_data() {
$user_id = $this->input->post('user_id');
return $this->Test_model->getUserData($user_id);
}
}
Test_model.php
class Test_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function getUserData($user_id) {
return $this->db->select("*")
->from("users")
->where("user_id", $user_id)
->get()->result_array();
}
}
The code in CITest.php
public test_controller() {
$_POST['useR_id'] = 22;
print_r($this->model->get_user_data());
}
should be like the following?
public test_controller() {
$_POST['useR_id'] = 22;
print_r($this->auth->get_user_data());
}

how do we set menu list globally

Initially I have to attach with each action :-
Here we first fetch menu detail then pass in to view section.
Class ManageadministratorController extends Controller {
public $data_menu;
public function __construct() {
$this->middleware('auth');
$obj = new General;
$this->data_menu=$obj->displaymenu();
}
public function index()
{
$obj = new General;
$permission = $obj->checkViewPermission("manageadministrator");
$query= Adminlogin::get();
return View::Make('admin.manageadministrator.manage',array('record'=>$query,'menu_list'=>$this->data_menu));
}
function add()
{
return View::Make('admin.manageadministrator.add',array('menu_list'=>$this->data_menu));
}
}
You can register a custom service provider or use AppServiceProvider:
public function boot()
{
$obj = new General;
$data_menu = $obj->displaymenu();
view()->composer('admin.manageadministrator', function($view) {
$view->with('menu_list', $data_menu);
});
}
Or use a dedicated class:
// app/Providers/AppServiceProvider.php
public function boot()
{
view()->composer('admin.manageadministrator', 'App\Http\Composers\MasterComposer');
}
// app/Http/Composers/MasterComposer.php
use Illuminate\Contracts\View\View;
class MasterComposer {
public function compose(View $view)
{
$obj = new General;
$data_menu = $obj->displaymenu();
$view->with('menu_list', $data_menu);
}
}

2 layouts in one controller

I have in my HomeController.php
// other pages layout
protected $layout = "layout";
protected $layout2 = "layout2";
// empty user object
protected $user;
// constructor
public function __construct()
{
}
public function getAbout()
{
// share main home page only
$this->layout->content = View::make('about');
}
// THIS IS NOT WORKING >>>>
public function getAboutnew()
{
// share main home page only
$this->layout2->content = View::make('about');
}
so the getAboutNew I am trying to use layout2 but I am getting an error:
ErrorException (E_UNKNOWN)
Attempt to assign property of non-object
How to fix this?
You need to make changes to your BaseController from which your HomeController is extending.
In your BaseController you have:
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
}
This converts the $this->layout (string) into the view object that you need.
Fix:
// BaseController, returning respective views for layouts
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
if ( ! is_null($this->layout2))
{
$this->layout2 = View::make($this->layout2);
}
}
// HomeController
public function getAbout()
{
$this->layout->content = View::make('about');
}
public function getAboutnew()
{
$this->layout2->content = View::make('about');
return $this->layout2;
// Note the additional return above.
//You need to do this whenever your layout is not the default $this->layout
}

Execute Query with Where Condition For ResultSet Zend Framework 2?

I have one tabel 'cms' which include cms page with 3 separate parent category(type) . when i call fetchAll() function which fetch all data but i want to only fetch data which parent category(type)='1' means i want to pass where condition and orderby condition in fetchAll() function.
My Cms.php page is:
<?php
namespace Front\Model;
use Zend\Db\TableGateway\AbstractTableGateway;
class Cms extends AbstractTableGateway {
public function __construct($adapter) {
$this->table = 'cms';
$this->adapter = $adapter;
}
public function fetchAll($id) {
return $this->select();
}
public function getCmsContent($id){
$id = (int) $id;
$rowset = $this->select(array('id'=>$id));
if (!$row = $rowset->current()){
throw new \Exception ('Row not found');
}
return $row;
}
}
My Controller is :FrontController.php is:
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Front\Model\Cms;
use Front\Model\Setting;
use Front\Model\Slider;
class FrontController extends AbstractActionController
{
public function indexAction()
{
return array('cms_data'=>$this->getCms()->fetchAll('1'));
}
public function getCms(){
return $this->getServiceLocator()->get('Front\Model\Cms');
}
}
My Model is:
namespace Front;
class Module
{
public function getAutoloaderConfig()
{
return array('Zend\Loader\StandardAutoloader' =>
array('namespaces' =>
array(__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
// Add this method:
public function getServiceConfig()
{
return array(
'factories' => array(
'Front\Model\Cms' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Front\Model\Cms($dbAdapter);
return $table;
},
),
);
}
}
?>
My View:index.php Page is:
<?php print_R($cms_data); ?>
Your question is not clear. Are you asking how to add Where clause to your query? If so, then this is it:
use Zend\Db\Sql\Predicate\Operator;
public function fetchAll($id) {
return $this->select()
->where(new Operator('type', Operator::OPERATOR_EQUAL_TO, $id);
}

Categories