saving data from joomla frontend - php

I was looking for a solution as to how to save data from joomla frontend. I came across the following code for controller and model which works perfectly. But I was looking for a standard practice like its done in the back end using jform, jtable etc ... In the following code (inside model), the saving technique do not look so appealing. And I am totally without any idea how the server side validations is implemented.
It might be confusing, so i would like to reiterate that in the backend we don't even have to write the add or save or update function, it is automatically handled by the core classes with both client and server side validation. So i was looking for something like that.
Controller
<?php
// No direct access.
defined('_JEXEC') or die;
// Include dependancy of the main controllerform class
jimport('joomla.application.component.controllerform');
class JobsControllerRegistration extends JControllerForm
{
public function getModel($name = 'Registration', $prefix = 'JobsModel', $config = array('ignore_request' => true))
{
return parent::getModel($name, $prefix, array('ignore_request' => false));
}
public function submit()
{
// Check for request forgeries.
JRequest::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('Registration');
// Get the data from the form POST
$data = JRequest::getVar('jform', array(), 'post', 'array');
$form = $model->getForm();
if (!$form) {
JError::raiseError(500, $model->getError());
return false;
}
// Now update the loaded data to the database via a function in the model
$upditem = $model->updItem($data);
// check if ok and display appropriate message. This can also have a redirect if desired.
if ($upditem) {
echo "<h2>Joining with us is successfully saved.</h2>";
} else {
echo "<h2>Joining with us faild.</h2>";
}
return true;
}
}
Model
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// Include dependancy of the main model form
jimport('joomla.application.component.modelform');
// import Joomla modelitem library
jimport('joomla.application.component.modelitem');
// Include dependancy of the dispatcher
jimport('joomla.event.dispatcher');
/**
* HelloWorld Model
*/
class JobsModelRegistration extends JModelForm
{
/**
* #var object item
*/
protected $item;
/**
* Get the data for a new qualification
*/
public function getForm($data = array(), $loadData = true)
{
$app = JFactory::getApplication('site');
// Get the form.
$form = $this->loadForm('com_jobs.registration', 'registration', array('control' => 'jform', 'load_data' => true),true);
if (empty($form)) {
return false;
}
return $form;
}
//Nwely added method for saving data
public function updItem($data)
{
// set the variables from the passed data
$fname = $data['fname'];
$lname = $data['lname'];
$age = $data['age'];
$city = $data['city'];
$telephone = $data['telephone'];
$email = $data['email'];
$comments = $data['comments'];
// set the data into a query to update the record
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->clear();
$db =& JFactory::getDBO();
$query = "INSERT INTO #__joinwithus ( `id`, `firstname`, `lastname`, `age`, `city`, `telephone`, `email`, `comment`)
VALUES (NULL,'" . $fname . "','" . $lname . "','" . $age . "','" . $city . "','" . $email . "','" . $telephone . "','" . $comments . "')";
$db->setQuery((string)$query);
if (!$db->query()) {
JError::raiseError(500, $db->getErrorMsg());
return false;
} else {
return true;
}
}
}
Can somebody kindly point me to a good tutorial or share me a component which deals with form in the frontend with joomla 2.5.

use the following code in your model
$data = $app->input->getArray($_POST);
$query = $db->getQuery(true);

You should be able to use jcontrollerform's methods directly, instead of writing your own submit()-method (and updItem()) like you do. I describe something similar here. This means you display your form the usual way using jform, and use action="index.php?option=com_jobs&task=save&view=registration&id=whateverid"
This way jcontrollerform->save() is used, which in turn calls your model's save(). (Hmmm, this probably means your model should extend JModelAdmin instead of JModelForm, to include the relevant methods. ) This will run all the necessary validation checks etc.
You might need to register paths for the model, table and form that you want to be using, like I do in the link.
You need to include the id in the url parameters if you edit existing data, because the jform[id] - parameter will be ignored.
Sorry I dont have any good tutorial or whatever for you, hope this helps.

Related

Why is include('../myscript.php') causing an error?

I've been trying to debug my PHP script and I've narrowed down the problem to the line
include "../classes.php";
at the top of my file team_manager.php which is where you see it below.
themes
my_theme
js
management
team_manager.php
project_manager.php
classes.php
footer.php
functions.php
Am I not doing the path correctly? Or could it be something wrong with the contents of classes.php? If it could be a problem with the file being included, below is the file, and let me know if anything immediately stands out as wrong.
<?php
final class MySqlInfo
{
const DBNAME = 'somedb';
const USER = 'someuser';
const PSSWD = 'somepassword';
const TEAMTABLENAME = 'sometablename';
public function getUser ( )
{
return self::USER;
}
public function getPassword ( )
{
return self::PSSWD;
}
}
final class MethodResult
{
public $succeeded;
public $message;
public MethodResult ( $succeededInit = NULL, $messageInit = NULL )
{
this->$succeeded = $succeededInit;
this->$message = $messageInit;
}
}
final class MySite
{
const ROOTURL = 'http://asite.com/subsite';
function getRootUrl()
{
return self::ROOTURL;
}
}
final class TeamManager
{
private $dbcon;
public function TeamManager ( )
{
$dbcon = mysqli_connect('localhost', MySqlInfo.getUser(), MySqlInfo::getPassword());
$dbcon->select_db(MySqlInfo::DBNAME);
// need to add error handling here
}
final public class TeamMember
{
public $name; // team member name
public $title; // team member title
public $bio; // team member bio
public $sord; // team member sort order
public $picfn; // team member profile picture file name
}
public function addMember ( TeamMember $M )
{
if ($this->$dbcon->connect_error)
{
return new MethodResult(false, 'Not connected to database');
}
$q = "INSERT INTO " . MySqlInfo::TEAMTABLENAME . " (" . implode( ',' array($M->name, $M->title, $M->bio, $M->sord, $M->picfn) ) . ") VALUES ('" . implode('\',\'', array($_POST['fullname'], $_POST['title'], $_POST['bio'], $_POST['sord'], $targetFileName)) . "')";
// ^ query for inserting member M to the database
if (!mysqli_query(this->$dbcon, $q))
{
return new MethodResult(false, 'Query to insert new team member failed');
}
return new MethodResult(true, 'Successfully added new member' . $M->name);
}
}
?>
include() might cause an error in case it can't find a file to be included. It's that simple. So you have to make sure that file exists before you include it. Also, never use relative paths like ../script.php, as they introduce a number of issues. And one major issue is that, some hosting providers don't allow relative paths due to security reasons.
So to make sure the file can be included, simply do the check for its existence:
<?php
// dirname(__FILE__) returns an absolute path of the current script
// which is being executed
$file = dirname(__FILE__) . '/script.php';
if (is_file($file)) {
include($file);
} else {
echo 'File does not exist';
}
Also, I see that you write code as an old-school. You might want to take a look at PSR-FIG standards.

Auto mapping method parameters to $_POST data (MVC)

Imagine I have a URL that loads a controller if the name matches (Ignoring any security issues with this at the moment hehe)
public function Load( $controller, $action = "Index" )
{
require_once( "Controllers/" . $controller . "Controller.php" );
$controllerName = $controller . "Controller";
$loadedController = new $controllerName();
$actionName = "ActionResult_" . $action;
$loadedController->$actionName();
}
Now imagine I want a log in form to send its $_POST details as parameters of the receiving controller launched above:
<?php
class ExcelUploadController extends Controller
{
public function ActionResult_Login( $username = NULL, $password = NULL )
{
// The parameters need to be mapped to the $_POST parameters names probably from the Load method somewhere and pumped in to the $loadedController->$actionName();
$post_username = $username;
$post_password = $password;
$this->ReturnView( "ExcelUpload/Index" );
}
}
?>
But also so that it does not matter what order the parameters are declared, it matches the parameter in the function based on the $_POST key.
How might I go about doing this, any ideas?
So to clarify if this doesn't make sense.. the method might look something like this:
public function Load( $controller, $action = "Index" )
{
require_once( "Controllers/" . $controller . "Controller.php" );
$controllerName = $controller . "Controller";
$loadedController = new $controllerName();
$actionName = "ActionResult_" . $action;
$checkIfPostData = $_POST;
if( isset( $checkIfPostData ) )
{
// Do some funky wang to map the following $loadedController->$actionName();
// with the username and password or any other $_POST keys so that in the calling method, I can grab hold of the $_POST values
}
$loadedController->$actionName();
}
What your are looking for is call_user_func_array()
EDIT, to reply to comment :
You have two options: rewrite all your function so that they accept only one array() as argument and you parse that array for values. A bit fastidious but it can be useful in some cases. Or you can request for the required argument of a function:
// This will create an object that is the definition of your object
$f = new ReflectionMethod($instance_of_object, $method_name);
$args = array();
// Loop trough params
foreach ($f->getParameters() as $param) {
// Check if parameters is sent through POST and if it is optional or not
if (!isset($_POST[$param->name]) && !$param->isOptional()) {
throw new Exception("You did not provide a value for all parameters");
}
if (isset($_POST[$param->name])) {
$args[] = $_POST[$param->name];
}
if ($param->name == 'args') {
$args[] = $_POST;
}
}
$result = call_user_func_array(array($instance_of_object, $method_name), $args);
That way your array will be properly constructed.
You can also add some specific treatment whether a parameter is optional or not (I guess you can understand how to do it from the code I gave you ;)
Since the data is being sent through POST you don't need to pass any parameters to your method:
class ExcelUploadController extends Controller {
private $userName;
private $login;
public function ActionResult_Login() {
$this->userName = $_POST['username'];
$this->login = $_POST['login'];
}
}
Don't forget to sanitize and validate the user input!

How to give source : path to jQuery autocomplete from Codeigniter

I have used jQuery auto complete on my Codeigniter application. But it's not working due to source path is broken.
This is my code:
jQuery(document).ready(function(){
$('.zipsearch').autocomplete({
source:'jQueryAutocompleteRelatedFields.php',
minLength:2,
select:function(evt, ui)
{
// when a zipcode is selected, populate related fields in this form
this.form.city.value = ui.item.city;
this.form.state.value = ui.item.state;
}
});
});
Currently file jQueryAutocompleteRelatedFields.php is on the following file path:
www\CI\application\views\search\jQueryAutocompleteRelatedFields.php
localhost\CI\index.php\search\searchItem
Is my browser path
How can I give the source?
SearchITem is function which coming under search controller,
Update : jQueryAutocompleteRelatedFields.php
<?php
class DB
{
const DATABASE = 'inventory';
const HOST = '127.0.0.1';
const USERNAME = 'root';
const PASSWORD = '';
static private $pdo;
static public function singleton()
{
if (!is_object(self::$pdo))
{
self::$pdo = new PDO('mysql:dbname=' . self::DATABASE . ';host=' . self::HOST,
self::USERNAME,
self::PASSWORD);
}
return self::$pdo;
}
private function __construct()
{
}
public function __clone()
{
throw new Exception('You may not clone the DB instance');
}
}
if (!isset($_REQUEST['term']))
{
die('([])');
}
$st = DB::singleton()
->prepare(
'select product_id, product_code, product_name ' .
'from tbl_product ' .
'where product_id like :product_id ' .
'order by product_id asc ' .
'limit 0,10');
$searchZip = $_REQUEST['term'] . '%';
$st->bindParam(':product_id', $searchZip, PDO::PARAM_STR);
$data = array();
if ($st->execute())
{
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
$data[] = array(
'value' => $row->product_id ,
'city' => $row->product_code ,
'state' => $row->product_name
);
}
}
echo json_encode($data);
flush();
You should use the browser path with forward slashes.
source: 'localhost/CI/index.php/search/searchitem',
You will have an issue moving this to a real web server though because you will want to use a relative path. I highly recommend setting up your local environment to be as similar as possible to the web server.
EDIT:
In CodeIgniter add the following code to your Search controller:
public function fetchList(){
// I assume your view is outputting an array ready to be encoded with JSON?
return json_encode($this->load->view('search/jQueryAutocompleteRelatedFields.php', array(), true));
// Try this if the code above doesn't work
return json_encode(array('item1','item2','item3','item4'));
}
Now point the AJAX source like this:
source: 'localhost/CI/index.php/search/fetchList',

PHP call to undefined method, but method is defined... (not the same as other 2 similar questions)

I am going through a tutorial to build up a mock Flickr site in PHP. I am getting to the point where we are adding in all the user CRUD. The user class has already been defined and has methods that are being used and work. But once I added the methods for create, update, delete and save it says it can't find any of them... I have tried modifying the methods that do work, and they don't change. So to me it seems like there is a cached version of the user class, because changes in the user.php file aren't being recognized. I have used ctrl+F5 to refresh the cache, but that doesn't change anything...
This is my directory set up
wamp
www
photo_gallery
includes
config.php
constants.php
database.php
database_object.php
functions.php
initialize.php
session.php
user.php
public
admin
index,php
login.php
logout.php
logfile.php
test.php
images
javascript
layouts
stylesheets
index.php
This is my initialize.php file that sets up the directory paths and loads all the files needed
<?php
// Define the core paths
// Define them as absolute paths to make sure that require_once works as expected
//DIRECTORY_SEPARATOR is a php pre-defined constant
// ( \ for Windows, / for Unix)
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
// checks if lib path exists if not defines the site root with the directory specified below
// ***** needs to be updated when switched directories, servers or computers
defined('SITE_ROOT') ? null :
define('SITE_ROOT', DS.'Users'.DS.'Alan D'.DS.'Desktop'.DS.'wamp'.DS.'www'.DS.'photo_gallery');
// Checks if lib path has been defined, if not it defines it using site path above
defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.DS.'includes');
// first load config
require_once(LIB_PATH.DS.'config.php');
// load basic functions that are available for all other files
require_once(LIB_PATH.DS.'functions.php');
// load core object classes for application
require_once(LIB_PATH.DS.'session.php');
require_once(LIB_PATH.DS.'database.php');
require_once(LIB_PATH.DS.'database_object.php');
// load database-related object classes
require_once(LIB_PATH.DS.'user.php');
?>
This is the user class, it was simpler then this when I was testing, but I continued to follow through the steps to make the methods able to be dropped into my other classes when I create them.
<?php
require_once('database.php');
class User extends DatabaseObject{
protected static $db_fields = array('id', 'user_name', 'password',
'first_name', 'last_name');
protected static $table_name="users";
public $id;
public $user_name;
public $password;
public $first_name;
public $last_name;
public function full_name(){
if(isset($this->first_name) && isset($this->last_name)){
return $this->first_name . " " . $this->last_name;
} else {
return "";
}
}
// authenticates user by checking if there is a row with the
// input user name and password, then returns the object if found
// if not it returns false
public static function authenticate($user_name="", $password=""){
global $database;
$user_name = $database->escape_values($user_name);
$password = $database->escape_values($password);
$sql = "SELECT * FROM users ";
$sql .= "WHERE user_name = '{$user_name}' ";
$sql .= "AND password = '{$password}' ";
$sql .= "LIMIT 1";
$result_array = self::find_by_sql($sql);
return !empty($result_array) ? array_shift($result_array) : false;
}
// checks to see if the given attribute exsits for the current object
private function has_attribute($attribute){
// associative array with all attributes key and value pairs
$object_vars = $this->attributes();
// just check if the key exists and return true or false
return array_key_exists($attribute, $object_vars);
}
// returns a key value hash of the objects variables and values
protected function attributes(){
// get_object_vars returns an associative array with all attributes
// (incl private) as the keys and their current values as value
// return get_object_vars($this);
// this goes through the db fields and populates the hash
$attributes = array();
foreach(self::$db_fields as $field){
if(property_exists($this, $field)){
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
// returns a sanitized (sql escaped) array of all the attributes
protected function sanitized_attributes(){
global $database;
$clean_attributes = array();
// sanitize the values before submitting
// Note: does not alter the actual value of each attribute
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
// this function check to see if the record is already there
// and determines whether to create or update.
public function save(){
return isset($this->id) ? $this->update() : $this->create();
}
public function create(){
global $database;
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO ".self::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)){
$this->id = $database->insert_id();
return true;
} else {
return false;
}
}
public function update(){
global $database;
$attributes = $this->sanitized_attributes();
// set up the key, value string needed for the update statement
foreach ($attributes as $key => $value){
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id='". $database->escape_value($this->id);
$database->query($sql);
return($database->affected_rows() == 1) ? true : false;
}
public function delete(){
global $database;
$sql = "DELETE FROM ".self::$table_name." ";
$sql .= "WHERE id=". $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
return($database->affected_rows() == 1) ? true : false;
}
}
?>
In the admin/test.php file it is set up like this
<?php
require_once('../../includes/initialize.php');
if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>
<?php include_layout_template('admin_header.php'); ?>
<?php
$user = new User();
$user->user_name = "jDoe";
$user->password = "pass";
$user->first_name = "Jamie";
$user->last_name = "Doe";
echo $user->full_name();
$user->save();
//$user = User::find_by_id(1);
//$user->password = "pass1";
//$user->update();
?>
<?php include_layout_template('admin_footer.php'); ?>
When I run that page I get the admin header layout to load, the full name is printed on the screen and directly below it says:
Fatal error: Call to undefined method User::save() in C:\wamp\www\photo_gallery\public\admin\test.php on line 17
The same was happening with create and update... but these functions do exist in the user.php file, I even emptied everything out of the methods to makes sure there was no bug in the php code inside of them.
Then I tried the test from the public folder, through public/index.php
<?php
require_once('../includes/initialize.php');
if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>
<?php include_layout_template('admin_header.php'); ?>
<?php
$user = new User();
$user->user_name = "jDoe";
$user->password = "pass";
$user->first_name = "Jamie";
$user->last_name = "Doe";
$user->full_name();
$user->create();
?>
<?php include_layout_template('admin_footer.php'); ?>
But this doesn't even load the admin header layout... and just gives me the same error as the other test file did. I am pretty positive that I am navigating to the correct path based on the directory set up.
For the life of me I cannot understand why/how the user object isn't being updated when I add things to the user class inside user.php. Or how I could use other methods I had previously defined in user, but they don't change when I modify them... Does php do any caching of objects that I am unaware of? I even pulled the user.php out of the includes directory... and everything still runs as explained above...
Any insight would be greatly appreciated. I have been searching around for a while now trying to find someone with a similar issue but I can't find one. Thanks for reading.
It seems in your initialize.php you have an additional directory in the SITE_ROOT definition compared to what you show in your directory structure. Do you still have another copy of this code perhaps in photo_gallery directory that this is actually including files from?
This is where all your includes are pointing to:
/Users/Alan D/Desktop/wamp/www/photo_gallery/includes

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);
}
?>

Categories