Added new method to the controller doesn't work in codeigniter - php
I am working on an existing project developed by codeigniter 2.1.4. When I add a new method to a controller and run it to the browser, it shows nothing. Even other methods under that controller also don't run if new method added to that controller. These controllers extends the following controller:
<?php
class MY_Controller extends CI_Controller {
public $data = array();
public $allowedUrl = array(
"super admin" => array("case_controllerler/deleteSingleCase","case_controller/quickPendingCaseSearch","case_controller/checkUniqueCaseNumber","case_controller/kharijCase","admin/index","case_controller/viewSatalementKhatianCopyApplication", "admin/saveAdmin","admin/addUser", "admin/allAdmin", "admin/suspendUser", "admin/activeUser", "admin/CustomSearchGL","admin/showMethod","admin/CustomSearchAction","admin/deleteUser","admin/showAllComplain","admin/singleAdminInfo","admin/updateAdminInfo","admin/successfullyUpdated","case_controller/downloadPendingCase",
"case_controller/addCase", "case_controller/store_data", "case_controller/caseSuccessfullyAdded", "case_controller/createCalender",
"case_controller/workingDaysCalender", "case_controller/editPendingCase","case_controller/saveEditedPendingCase","case_controller/EditmissCase","case_controller/UpdateMisccase",
"case_controller/pending", "case_controller/allCase", "case_controller/searchCase", "case_controller/singleCase","case_controller/testAjax","case_controller/DeleteLandData","case_controller/SaveNEwLandInfo","case_controller/DeleteApplicantinfo",
"case_controller/nextDateFromGivenDate","case_controller/downloadArchiveCase","case_controller/sendSms","case_controller/secondSms","case_controller/thirdSms","case_controller/fourthSms","case_controller/fiveSms","case_controller/CustomSms","case_controller/monthAllreadyExit",
"register_control/AddTohsil","register_control/TohsilEntry","register_control/EditTohsil","register_control/updatetohsil",
"register_control/AddMouja","register_control/MoujaEntry","register_control/EditMouja","register_control/updateMouja",
"register_control/AddMutationAsistant","register_control/MutationAsistantEntry","register_control/EditMutationAsistant","register_control/updateMutationAsistant",
"register_control/AddKhotiyan","register_control/moujaquery","register_control/saveKhotiyan","register_control/saveKhotiyanFile",
"register_control/FindKhotiyan","register_control/SearchKhotiyan","register_control/DeleteKhotiyan","register_control/Editkhotiyan",
"register_control/AddNewKhotiyanUnderKhotiyanId","register_control/saveNewKhotiyan","register_control/UpdateKhotiyan","register_control/Getjolmohol",
"register_control/Tamil","register_control/EntryTamilFormat","register_control/createcellfortamil","register_control/editTamil","register_control/UpdateTamil","register_control/DeleteTamil","register_control/Imgdownload",
"dashboard/DashboardHome","dashboard/viewFullreport","dashboard/tohsilviewlist","dashboard/tohsilviewlistoverdate","dashboard/namjariviewlist","dashboard/namjariviewlistoverdate","dashboard/kanongopendingviewlist","dashboard/kanongooverdateviewlist","dashboard/aclandPendingeviewlist","dashboard/aclandoverdateviewlist","dashboard/waitingpendingviewlist","dashboard/waitingooverdateviewlist",
"admin/DeleteComplains","admin/fullviewcomplains", "register_nine/Newentry","register_nine/SaveData","register_nine/Search","register_nine/viewapplication",
"register_nine/editapplication","register_nine/Deleteapplication","register_nine/Preview","register_nine/UpdateApplication",
"register_nine/SearchForPreview","register_nine/paginationData","admin/GovLandEntry","admin/savegovtLandInfo","admin/GovLandQuery","admin/govtLandInfoQuery","admin/EditGovtLand",
"admin/UpdategovtLandInfo","admin/DeleteGovtLandInfo","admin/govtLandInfoQueryByType",
"case_controller/AddmissCase","case_controller/SaveMissCase","case_controller/MIssCassUpdate","case_controller/UpdateInfoMissCase","case_controller/MiscSmsToplaintiff",
"case_controller/EditMIssCaseUpdate","case_controller/UpdateStatus","case_controller/DeletemissCasestatus","case_controller/CheckGovtLand",
"case_controller/FinishMisscase","case_controller/DeletemissCase","case_controller/ArchivemissCase","case_controller/ViewMIssCassUpdate","case_controller/SearchActionByNameOrNId","case_controller/SearchActionBydag",
"case_controller/SearchmissCase","case_controller/SearchMisscaseAction","case_controller/viewPorcaApplication","case_controller/DeletePorcaapplication","case_controller/ArchivePorcaApplication","case_controller/approvalsms",
"case_controller/ApprovePoRcaApliCation","case_controller/fullviewPrcaApplication","register_control/RemoveKhotiyanFile","case_controller/SaveMissCaseAttchment",
"register_control/DeleteKHotiyanFile","register_control/ViewTamil","register_control/NewAddKhotiyanFile","register_control/TamilDownload","register_control/RegisterONe","register_control/FileInventory"
,"other_registers/EntryDailyIncome","other_registers/SaveDailyINcome","other_registers/inqueryAndSubmit","other_registers/SearchActionOfInquery","other_registers/DeliveryToBank","other_registers/deliverySuccess",
"other_registers/searchCashRegister","other_registers/SearchActionregisterthree","other_registers/SearchActionregisterthreebyStauts","other_registers/registerseventeenOfTohsil","other_registers/DemandRegister","other_registers/miscellenousPaymentRegister",
"other_registers/registerseventeenOfAcland","admin/showAllOpinion","admin/Deleteopinion","admin/fullviewopinion","mutation_controller/DownloadMutationApplication","mutation_controller/AllMutationApplications","mutation_controller/DetailsMutationAppliCation",
"mutation_controller/accecptApplicationSms","mutation_controller/DeleteMutationApplication","dashboard/TohsilPieChart","other_registers/SavedemandRegisterSix","other_registers/SearchAndDelivaryRegisterSix"
,"other_registers/SearchActionOfInqueryRegisterSix","other_registers/RegisterSixDelivery","other_registers/registerSixdeliverySuccess","other_registers/SavePaymentRegisterSeven",
"other_registers/SearchAndDelivaryRegisterSeven","other_registers/SearchActionOfInqueryRegisterSeven","other_registers/RegisterSevenDelivery","other_registers/registerSevendeliverySuccess","case_controller/ChangeMutationAsistant",
"case_controller/ActionChangeMutationAsistant","case_controller/FeedbackMiscCaseUpdate","case_controller/FeedbackUpdateInfoMissCase","admin/EditUser","admin/updateAdminInfobySuperAdmin", "case_controller/EditMIssCaseUpdateFeedback",
"case_controller/UpdateStatusFeedback","case_controller/PrintMIsscassInformation","case_controller/viewArchiveCase","case_controller/deleteArchiveSingleCase","case_controller/RuningMiscCase","dashboard/CaseCounter",
"other_registers/deleteDailyEntryRegisterThree","other_registers/deleteDailyEntryRegistersix","other_registers/deleteDailyEntryRegisterseven","case_controller/fullviewArchivePrcaApplication","case_controller/OrderSheet","case_controller/SaveOrderInfo","case_controller/PrintOrderSheet",
"case_controller/ViewLedger","case_controller/ProposalView","case_controller/SaveProposalInfo","case_controller/PrintProposalView","case_controller/CaseNotice","case_controller/PrintNoticeView","case_controller/SecondPagePrintProposalView",
"case_controller/UpdateCaseLandInfo","case_controller/SaveScratchMap","case_controller/UpdateCaseApplicantInfo","case_controller/TohsilWisePendingCaselist"),
"admin" => array("case_controller/addCase","case_controller/organizeDateFormat","case_controller/createCalender","case_controller/EditmissCase","case_controller/UpdateMisccase","case_controller/DeleteLandData","case_controller/SaveNEwLandInfo","case_controller/DeleteApplicantinfo",
"case_controller/assendingCalender","case_controller/monthAllreadyExit","case_controller/changeDateFromat","case_controller/testAjax","case_controller/nextDateFromGivenDate",
"case_controller/store_data","case_controller/caseSuccessfullyAdded","case_controller/allCase","case_controller/searchCase","case_controller/singleCase",
"case_controller/pending","case_controller/quickPendingCaseSearch","case_controller/kharijCase","case_controller/editPendingCase","case_controller/saveEditedPendingCase",
"case_controller/downloadArchiveCase","case_controller/downloadPendingCase","case_controller/sendSms","case_controller/secondSms","case_controller/thirdSms",
"case_controller/fourthSms","case_controller/fiveSms","case_controller/CustomSms","case_controller/checkUniqueCaseNumber","case_controller/AddmissCase","case_controller/MiscSmsToplaintiff","case_controller/ViewLedger","case_controller/CaseNotice",
"case_controller/SaveMissCase","case_controller/MIssCassUpdate","case_controller/UpdateInfoMissCase","case_controller/EditMIssCaseUpdate","case_controller/UpdateStatus",
"case_controller/FinishMisscase","case_controller/ArchivemissCase","case_controller/ViewMIssCassUpdate","case_controller/RuningMiscCase","case_controller/SaveMissCaseAttchment",
"case_controller/SearchmissCase","case_controller/SearchMisscaseAction","case_controller/viewPorcaApplication","case_controller/ArchivePorcaApplication",
"case_controller/ApprovePoRcaApliCation","case_controller/fullviewPrcaApplication","case_controller/SearchActionByNameOrNId","case_controller/SearchActionBydag",
"case_controller/approvalsms","case_controller/ChangeMutationAsistant","case_controller/ActionChangeMutationAsistant","case_controller/FeedbackMiscCaseUpdate",
"case_controller/FeedbackUpdateInfoMissCase","case_controller/EditMIssCaseUpdateFeedback","case_controller/UpdateStatusFeedback","case_controller/PrintMIsscassInformation",
"case_controller/viewArchiveCase","case_controller/RuningMiscCase","case_controller/viewSatalementKhatianCopyApplication","case_controller/fullviewArchivePrcaApplication",
"dashboard/DashboardHome","dashboard/viewFullreport","dashboard/tohsilviewlist","dashboard/tohsilviewlistoverdate","dashboard/namjariviewlist",
"dashboard/namjariviewlistoverdate","dashboard/kanongopendingviewlist","dashboard/kanongooverdateviewlist","dashboard/aclandPendingeviewlist",
"dashboard/aclandoverdateviewlist","dashboard/waitingpendingviewlist","dashboard/waitingooverdateviewlist","dashboard/TohsilPieChart","dashboard/CaseCounter",
"mutation_controller/AllMutationApplications","mutation_controller/DetailsMutationAppliCation","mutation_controller/DownloadMutationApplication",
"mutation_controller/accecptApplicationSms","mutation_controller/DeleteMutationApplication","mutation_controller/MutationForm",
"other_registers/EntryDailyIncome","other_registers/SaveDailyINcome","other_registers/inqueryAndSubmit","other_registers/SearchActionOfInquery",
"other_registers/searchCashRegister","other_registers/SearchActionregisterthree","other_registers/SearchActionregisterthree","other_registers/SearchActionregisterthreebyStauts",
"other_registers/registerseventeenOfTohsil","other_registers/DemandRegister","other_registers/miscellenousPaymentRegister","other_registers/registerseventeenOfAcland",
"other_registers/SavedemandRegisterSix","other_registers/SearchAndDelivaryRegisterSix","other_registers/SearchActionOfInqueryRegisterSix","other_registers/RegisterSixDelivery",
"other_registers/registerSixdeliverySuccess","other_registers/SavePaymentRegisterSeven","other_registers/SearchAndDelivaryRegisterSeven",
"other_registers/SearchActionOfInqueryRegisterSeven","other_registers/RegisterSevenDelivery","other_registers/registerSevendeliverySuccess",
"register_control/moujaquery","register_control/getmoujaAndMObile","register_control/AddKhotiyan","register_control/saveKhotiyan","register_control/saveKhotiyanFile",
"register_control/NewAddKhotiyanFile","register_control/FindKhotiyan","register_control/SearchKhotiyan","register_control/Editkhotiyan","register_control/UpdateKhotiyan",
"register_control/Tamil","register_control/createcellfortamil","register_control/EntryTamilFormat","register_control/editTamil","register_control/UpdateTamil",
"register_control/ViewTamil","register_control/Imgdownload","register_control/TamilDownload","register_control/RegisterONe","register_control/Getjolmohol",
"admin/index","admin/singleAdminInfo","admin/updateAdminInfo","admin/successfullyUpdated","admin/GovLandEntry","admin/savegovtLandInfo","admin/GovLandQuery","admin/govtLandInfoQuery",
"admin/EditGovtLand","admin/UpdategovtLandInfo","admin/govtLandInfoQueryByType","admin/allAdmin","admin/CustomSearchGL","admin/showMethod","admin/CustomSearchAction",
"register_nine/Newentry","register_nine/Search","register_nine/viewapplication","register_nine/editapplication","register_nine/UpdateApplication",
"register_nine/Preview","register_nine/SearchForPreview","register_nine/paginationData","case_controller/UpdateCaseLandInfo","case_controller/SaveScratchMap","case_controller/UpdateCaseApplicantInfo"),
"general user" => array("case_controller/quickPendingCaseSearch","case_controller/kharijCase","case_controller/pending", "case_controller/allCase", "case_controller/searchCase", "case_controller/singleCase", "admin/index","case_controller/downloadPendingCase","admin/singleAdminInfo","admin/updateAdminInfo","admin/successfullyUpdated",)
);
public function __construct() {
parent::__construct();
$this->isLoggedIn();
$this->isPermitedToAccess();
}
public function isLoggedIn() {
if ($this->session->userdata('logged_in') === FALSE) {
redirect('login/index');
}
}
//end of the is logged in
public function isPermitedToAccess() {
$userType = $this->session->userdata("type");
$currentUrl = $this->uri->segment(1) . "/" . $this->uri->segment(2);
if (array_search($currentUrl, $this->allowedUrl[$userType]) === FALSE) {
redirect("admin/index");
}
}
}
I tried to add my new method to $allowedUrl variable. But it didn't work. Can any one please give me any idea to solve this problem. I am stuck on it.
Did you try to assign the value for $allowedUrl inside __construct function, I think it will work!
Related
Codeigniter4 Routing Failing
I have a problem with routing on my website as it's not working at all. At the beginning I wanted to have different Controllers for differetn tabs, but in the end I have changed that to view pages from the Home controller, but even that doesnt work. Here is my Home controller - index and connection to Model works fine but the travel() function doesnt <?php namespace App\Controllers; use App\Models\HomeMod; use \Codeigniter\Controller; class Home extends BaseController { public function index() { $this->homeMod = new HomeMod(); $data = array(); $data['total'] = number_format($this->totalCases('total')); echo view('header'); echo view('welcome_message', $data); echo view('footer'); } protected function totalCases(String $columnName) : String{ $result = $this->homeMod->findColumn($columnName); return count($result) > 0 ? $result[0] : "0"; } public function travel() { return view('travel'); } public function getPostCodeCases() { if(!IS_AJAX) return; var_dump("inside"); die(); } } I cannot reach the getPostCodeCases() function either (the ajax call in js file works fine, its just not reaching this function). And my routes file - as you can see i have tries with different variations $routes->get('/', 'Home::index'); // $routes->get('/getPostCodeCases', 'Home::getPostCodeCases'); $routes->post('/getPostCodeCases', 'Home::getPostCodeCases'); $routes->match(['get', 'post'],'/getPostCodeCases', 'Home::getPostCodeCases'); $routes->get("travel", "Travel::index"); // $routes->add('/travel', 'Travel::index'); // $routes->add('travel', 'Home::travel'); // $routes->add('/travel/(:any)', 'Travel::index'); My base url: https://localhost/CI and $indexPage = '' (in App.php). I am sure I have missed something, somewhere but not sure where... Could someone help me to resolve this problem ?
CakePHP 4 sub view or sub action routing
In cakePHP 4 I have a controller and view.php connected with it. I can use a route like this: sitename.com/projects/45, where 45 - is sample project ID. Using this url I can reach a page with the content of particular project. But If I want to construct something like a page of settings of this project, how I have to do it? For example via url sitename.com/projects/45/settings Help please
It's simple: // sitename.com/projects/45 // public function view($id) { ... } // sitename.com/projects/45/settings public function view($id, $passed = null) { if($passed == 'settings') { // do ... } } or public function view($id) { $passed = $this->getRequest()->getParam('pass'); if (in_array('settings', $passed)) { // do ... } }
accessibilty issue with codeigniter session library
I'm working on user login system in codeigniter. When user clicks on login button the username and password are verified and the data is store in $this->session->set_userdata($arr); session library and the page redirects to home.php. Till here works fine but when is try to access the session in home.php as print_r($this->session->userdata);. it give me this errors Here is the Controller code : Login.php function login_user(){ $login_btn = $this->input->post('login_btn'); if($login_btn == TRUE){ $arr['login'] = array( 'username'=>$this->input->post('username'), 'password'=>$this->input->post('password') ); $query = $this->Login_model->users_login($arr); if($query->num_rows() > 0 && $query->num_rows() == 1){ $this->load->library('session'); $this->session->set_userdata($arr); redirect('Login/redirec_To_home','refresh'); } else { $this->index(); } } else { $this->index(); } } function redirec_To_home(){ $this->load->view('login/home'); } Here is the view html file name : path views/login/home.php <?php print_r($this->session->userdata); //ERRORS SHOWN IN THIS LINE NUMBER : 13 ?> THANKS IN ADVANCE
Please go to application/config/autoload.php in your project directory and search libraries, after that add session to this line which will look like this. $autoload['libraries'] = array('session');
In the __construct area you need to reload the session library using get instance in libraries https://www.codeigniter.com/user_guide/general/ancillary_classes.html https://www.codeigniter.com/user_guide/general/creating_libraries.html#utilizing-codeigniter-resources-within-your-library class Example { protected $CI; // We'll use a constructor, as you can't directly call a function // from a property definition. public function __construct() { // Assign the CodeIgniter super-object $this->CI =& get_instance(); $this->CI->load->library('session'); $this->CI->load->model('login_model'); } public function somefunction() { $this->CI->input->post('username'); $this->CI->input->post('password'); $user_model = $this->CI->login_model->user_login(); $sesstion_data = array('user_id' => '1'); $this->CI->session->set_userdata($sesstion_data); } }
How do I use a controller within a controller?
I am using Kohana 3.2 and I am having problems calling the ouput of a controller in another controller. What I want... In some pages I have got a menu, and in others I don't. I want to use make use of the flexability of the HMVC request system. In the controller of a page I want to call another controller which is responsible for the creation of the menu. What I have a the moment: file menu.php: <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Menu extends Controller { private $_model = null; public function __construct(Request $request, Response $response) { parent::__construct($request, $response); $this->_model = Model::factory('menu'); } public function action_getMenu() { $content = array(); $content['menuItems'] = $this->_model->getMenuItems(); // Render and output. $this->request->response = View::factory('blocks/menu', $content); //echo '<pre>'; print_r($this->request->response->render()); echo '</pre>'; die(); } } somepage.php public function action_index() { $this->template->title = 'someTitle';; $contentData['pageTitle'] = 'someTitle'; $contentData['contentData'] = 'someData'; #include the menu $menuBlock = Request::factory('menu/getMenu')->execute(); $menuData = array('menu' => $menuBlock); $this->template->menu = View::factory('pages/menu')->set('menu',$menuData); $this->template->content = View::factory('pages/somePage', $contentData); $view = $this->response->body($this->template); $this->response->body($view); } If I uncomment the following line in menu.php, I see the menu rendered: //echo '<pre>'; print_r($this->request->response->render()); echo '</pre>'; die(); So I guess that part is alright. The problem is in the following line in somepage.php: $menuBlock = Request::factory('menu/getMenu')->execute(); This gives me back a response object. Whatever I do, I do not get the output in $this->template->menu. $this->template->menu = View::factory('pages/menu')->set('menu',$menuData); What must I do to have $this->template->menu contain the view, so I can use it correctly? I hope this all makes sense. This is the way I would like to do it, but maybe I am completely on the wrong track.
I would do it this way: class Controller_Menu extends Controller { public function action_build() { // Load the menu view. $view = View::factory('navigation/menu'); // Return view as response- $this->response->body($view->render()); } } In your controller get the menu as follows: // Make request and get response body. $menu = Request::factory('menu/build')->execute()->body(); // e.g. assign menu to template sidebar. $this->template->sidebar = Request:.factory('menu/build')->execute()->body(); I would not use the __construct method in your controllers. Use before() instead, this is sufficient for most of the problems (for example auth): public function before() { // Call aprent before, must be done here. parent::before(); // e.g. heck whether user is logged in. if ( !Auth::instance()->logged_in() ) { //Redirect if not logged in or something like this. } }
I found the answer to my problem in less than an hour after asking. I just forgot to put it here. In somePage.php change : $menuBlock = Request::factory('menu/getMenu')->execute(); $menuData = array('menu' => $menuBlock); $this->template->menu = View::factory('pages/menu')->set('menu',$menuData); To: $this->template->menu = Request::factory('menu/getMenuBlock')->execute()->body(); And in menu.php change: $this->request->response = View::factory('blocks/menu', $content); To: $request = View::factory('blocks/menu', $content); $this->response->body($request); I hope this will help someone else.
An example of an MVC controller
I have been reading a lot about how and why to use an MVC approach in an application. I have seen and understand examples of a Model, I have seen and understand examples of the View.... but I am STILL kind of fuzzy on the controller. I would really love to see a thorough enough example of a controller(s). (in PHP if possible, but any language will help) Thank you. PS: It would also be great if I could see an example of an index.php page, which decides which controller to use and how. EDIT: I know what the job of the controller is, I just don't really understand how to accomplish this in OOP.
Request example Put something like this in your index.php: <?php // Holds data like $baseUrl etc. include 'config.php'; $requestUrl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; $requestString = substr($requestUrl, strlen($baseUrl)); $urlParams = explode('/', $requestString); // TODO: Consider security (see comments) $controllerName = ucfirst(array_shift($urlParams)).'Controller'; $actionName = strtolower(array_shift($urlParams)).'Action'; // Here you should probably gather the rest as params // Call the action $controller = new $controllerName; $controller->$actionName(); Really basic, but you get the idea... (I also didn't take care of loading the controller class, but I guess that can be done either via autoloading or you know how to do it.) Simple controller example (controllers/login.php): <?php class LoginController { function loginAction() { $username = $this->request->get('username'); $password = $this->request->get('password'); $this->loadModel('users'); if ($this->users->validate($username, $password)) { $userData = $this->users->fetch($username); AuthStorage::save($username, $userData); $this->redirect('secret_area'); } else { $this->view->message = 'Invalid login'; $this->view->render('error'); } } function logoutAction() { if (AuthStorage::logged()) { AuthStorage::remove(); $this->redirect('index'); } else { $this->view->message = 'You are not logged in.'; $this->view->render('error'); } } } As you see, the controller takes care of the "flow" of the application - the so-called application logic. It does not take care about data storage and presentation. It rather gathers all the necessary data (depending on the current request) and assigns it to the view... Note that this would not work with any framework I know, but I'm sure you know what the functions are supposed to do.
Imagine three screens in a UI, a screen where a user enters some search criteria, a screen where a list of summaries of matching records is displayed and a screen where, once a record is selected it is displayed for editing. There will be some logic relating to the initial search on the lines of if search criteria are matched by no records redisplay criteria screen, with message saying "none found" else if search criteria are matched by exactly one record display edit screen with chosen record else (we have lots of records) display list screen with matching records Where should that logic go? Not in the view or model surely? Hence this is the job of the controller. The controller would also be responsible for taking the criteria and invoking the Model method for the search.
<?php class App { protected static $router; public static function getRouter() { return self::$router; } public static function run($uri) { self::$router = new Router($uri); //get controller class $controller_class = ucfirst(self::$router->getController()) . 'Controller'; //get method $controller_method = strtolower((self::$router->getMethodPrefix() != "" ? self::$router->getMethodPrefix() . '_' : '') . self::$router->getAction()); if(method_exists($controller_class, $controller_method)){ $controller_obj = new $controller_class(); $view_path = $controller_obj->$controller_method(); $view_obj = new View($controller_obj->getData(), $view_path); $content = $view_obj->render(); }else{ throw new Exception("Called method does not exists!"); } //layout $route_path = self::getRouter()->getRoute(); $layout = ROOT . '/views/layout/' . $route_path . '.phtml'; $layout_view_obj = new View(compact('content'), $layout); echo $layout_view_obj->render(); } public static function redirect($uri){ print("<script>window.location.href='{$uri}'</script>"); exit(); } }
<?php class Router { protected $uri; protected $controller; protected $action; protected $params; protected $route; protected $method_prefix; /** * * #return mixed */ function getUri() { return $this->uri; } /** * * #return mixed */ function getController() { return $this->controller; } /** * * #return mixed */ function getAction() { return $this->action; } /** * * #return mixed */ function getParams() { return $this->params; } function getRoute() { return $this->route; } function getMethodPrefix() { return $this->method_prefix; } public function __construct($uri) { $this->uri = urldecode(trim($uri, "/")); //defaults $routes = Config::get("routes"); $this->route = Config::get("default_route"); $this->controller = Config::get("default_controller"); $this->action = Config::get("default_action"); $this->method_prefix= isset($routes[$this->route]) ? $routes[$this->route] : ''; //get uri params $uri_parts = explode("?", $this->uri); $path = $uri_parts[0]; $path_parts = explode("/", $path); if(count($path_parts)){ //get route if(in_array(strtolower(current($path_parts)), array_keys($routes))){ $this->route = strtolower(current($path_parts)); $this->method_prefix = isset($routes[$this->route]) ? $routes[$this->route] : ''; array_shift($path_parts); } //get controller if(current($path_parts)){ $this->controller = strtolower(current($path_parts)); array_shift($path_parts); } //get action if(current($path_parts)){ $this->action = strtolower(current($path_parts)); array_shift($path_parts); } //reset is for parameters //$this->params = $path_parts; //processing params from url to array $aParams = array(); if(current($path_parts)){ for($i=0; $i<count($path_parts); $i++){ $aParams[$path_parts[$i]] = isset($path_parts[$i+1]) ? $path_parts[$i+1] : null; $i++; } } $this->params = (object)$aParams; } } }
Create folder structure Setup .htaccess & virtual hosts Create config class to build config array Controller Create router class with protected non static, with getters Create init.php with config include & autoload and include paths (lib, controlelrs,models) Create config file with routes, default values (route, controllers, action) Set values in router - defaults Set uri paths, explode the uri and set route, controller, action, params ,process params. Create app class to run the application by passing uri - (protected router obj, run func) Create controller parent class to inherit all other controllers (protected data, model, params - non static) set data, params in constructor. Create controller and extend with above parent class and add default method. Call the controller class and method in run function. method has to be with prefix. Call the method if exisist Views Create a parent view class to generate views. (data, path) with default path, set controller, , render funcs to return the full tempalte path (non static) Create render function with ob_start(), ob_get_clean to return and send the content to browser. Change app class to parse the data to view class. if path is returned, pass to view class too. Layouts..layout is depend on router. re parse the layout html to view and render
Please check this: <?php global $conn; require_once("../config/database.php"); require_once("../config/model.php"); $conn= new Db; $event = isset($_GET['event']) ? $_GET['event'] : ''; if ($event == 'save') { if($conn->insert("employee", $_POST)){ $data = array( 'success' => true, 'message' => 'Saving Successful!', ); } echo json_encode($data); } if ($event == 'update') { if($conn->update("employee", $_POST, "id=" . $_POST['id'])){ $data = array( 'success' => true, 'message' => 'Update Successful!', ); } echo json_encode($data); } if ($event == 'delete') { if($conn->delete("employee", "id=" . $_POST['id'])){ $data = array( 'success' => true, 'message' => 'Delete Successful!', ); } echo json_encode($data); } if ($event == 'edit') { $data = $conn->get("select * from employee where id={$_POST['id']};")[0]; echo json_encode($data); } ?>