MVC view-controller - php

I start to learning MVC and I write my own MVC pattern, and I can do only main-controller and main-view, but I can't understand how to make another controller/action and I want to make some link from my main-view to another page. So I have next folders and and next simle code:
In my index.php I have simple:
<?php
ini_set('display_errors',1);
require_once 'myapp/bootstrap.php';
Next, in my bootstrap.php I connect my base classes view.php, controller.php, route.php and I run the Route function run():
<?php
require_once 'base/view.php';
require_once 'base/controller.php';
require_once 'base/route.php';
include_once 'Numbers/Words.php';
Route::run(); //start routing
?>
In my route.php I write this function run()
<?php
class Route
{
static function run()
{
// controller and action by defalt
$controller_name = 'Main';
$action_name = 'index';
$routes = explode('/', $_SERVER['REQUEST_URI']);
// get controller name
if ( !empty($routes[1]) )
{
$controller_name = $routes[1];
}
// get action name
if ( !empty($routes[2]) )
{
$action_name = $routes[2];
}
// add prefix
$controller_name = 'Controller_'.$controller_name;
$action_name = 'action_'.$action_name;
// add file with controller class
$controller_file = strtolower($controller_name).'.php';
$controller_path = "myapp/controllers/".$controller_file;
if(file_exists($controller_path))
{
include "myapp/controllers/".$controller_file;
}
else
{
Route::ErrorPage404();
}
// create controller
$controller = new $controller_name;
$action = $action_name;
if(method_exists($controller, $action))
{
// invoke action of controller
$controller->$action();
}
else
{
Route::ErrorPage404();
}
}
function ErrorPage404()
{
$host = 'http://'.$_SERVER['HTTP_HOST'].'/';
header('HTTP/1.1 404 Not Found');
header("Status: 404 Not Found");
header('Location:'.$host.'404');
}
}
It is defines my controllers and acrions routes.
And I also have my Controller_Main:
<?php
class Controller_Main extends Controller
{
function action_index()
{
$this->view->generate('main_view.php', 'template_view.php');
}
}
It loads my view and tamplate:
<div class="title">
<h1>Paymentwall PHP Test</h1>
<h2>Number To String Convertion</h2>
</div>
<div class="convertion_form">
<form name="form" class="form" method="POST" action="main/index">
<label>Enter your Number Please:</label>
<input class="number_input" type="text" name="number_input">
<input type="submit" value="Convert">
</form>
</div>
Tamplate:
<!DOCTYPE html>
<html>
<head>
<title>Main Page</title>
<link rel="stylesheet" href="http://localhost:81/css/style.css">
<meta charset="utf-8">
</head>
<body>
<?php include 'myapp/views/'.$content_view; ?>
</body>
</html>
So, my question is - what I need to do in my route.php to create another controller with action, and load another veiw? And how to write a link in my Main_View to another view? And I also have some web form, what I need to write in action="" ???
Please help me because I can not understand myself and find the answer.

You can create another action in your controller like this:
public function action_submit()
{
$this->view->generate('blabla');
}
And link it as /main/submit or you can create a new controller file and put some actions in it. Anyway look into some frameworks, CodeIgniter would be good for beginner, but don't stop on it once you understand how it works you can learn more complex ones, eventually coming to Symfony2/ZF2.
Edit: Actually better learn on your mistakes first, it will give you much better in-depth knowledge. And about frameworks - replace CodeIgniter (yeah it's shit, I just remember that I was learning with it at my first steps) with Silex.

Related

unrequire a php file

Im working on a website - just learning to improve my coding.
I have a routing system which works like this:
/config/routes.php:
$route->add('/' , function() {
require_once("/application/pages/index.php");
});
$route->add('/register', function() {
require_once("/application/pages/register.php");
});
$route->add('/login', function() {
require_once("/application/pages/login.php");
});
$route->add('/logout', function() {
require_once("/application/pages/logout.php");
});
$route->add('/panel', function() {
require_once('/application/pages/panel/index.php');
});
And in my index.php:
require_once('application/pages/header.php');
include('config/routes.php');
require_once('application/pages/footer.php');
Everything works fine but I need a different header.php and footer.php for when the user goes into the panel. file: /application/pages/panel/index.php
When I require_once a new header file in the panel/index.php then both the new and old header file is loaded. How can I unrequire the header and footer files in the /panel/index.php so I can require different ones? Any suggestions?
Note: Routing comes from an MVC design pattern, you should keep your controllers separate from your views.
Templates and Views could be kept separate, also. This meaning our directory set-up can look something like this:
- Templates
- header_one.php
- footer_one.php
- header_two.php
- footer_two.php
- Views
- index.php
- someOtherBody.php
Here is a simple, but unfinished (that is your challenge) example of an Object that could do what I am explaining:
class Page {
private $template_path = dirname(dirname(__FILE__)) . '/templates/';
private $view_path = dirname(dirname(__FILE__)) . '/views/';
protected $header;
protected $footer;
protected $body;
public function setHeader($file_name)
{
if(is_readable($this->template_path . $file_name))
{
$this->header = $this->template_path . $file_name;
return $this;
}
// add an exception
}
/* TODO: */
public function setFooter() {}
public function setBody() {}
/* Render page */
public function render()
{
$page = [$this->header,$this->body,$this->footer];
foreach($page as $file)
{
require_once($file);
}
}
}
The idea here is that we can set our page layout, using the above object, within the route method closure, then render / require all the files after the logic.
$route->add('/', function() {
$page = new Page();
$page->setHeader('header_one.php')
->setBody('index.php')
->setFooter('footer_one.php');
/* todo: add your logic here */
$page->render();
});
Each route can now have its own header, footer and body.
Hope this helped.
At your place, I will do something like that :
Use out buffer and check if the file is already required. I give you an quick example but adapt the code for you.
And check the function : http://php.net/manual/en/function.get-included-files.php
$route->add('/panel', function() {
include_once('YOUR_SPECIFIC_PATH/header.php');
require_once('/application/pages/panel/index.php');
include_once('YOUR_SPECIFIC_PATH_header/footer.php');
});
And :
ob_start();
include_once('config/routes.php');
$mainContent = ob_get_contents();
ob_end_clean();
include_once('application/pages/header.php');
echo $mainContent;
include_once('application/pages/footer.php');
I've not the time for help more sorry but I can explain later if you need
This solution requires you to have a header.php and footer.php in each folder where your sub-controllers (application/<module name>/index.php) are.
index.php only call your sub-controllers via routing:
// require not include, because "no routing" = "no web site" ;)
require_once('config/routes.php');
application/pages/index.php include appropriate header/footer w/ relative path
require_once('header.php');
// page code
require_once('footer.php');
application/register/index.php include appropriate header/footer w/ relative path
require_once('header.php');
// page code
require_once('footer.php');
etc
#KDOT , thanks you for your help but using your code I was getting an error that I could not fix:
Call to a member function setBody() on null
but thanks to your code, I managed to rewrite the class my way and now it works ;)
Thanks again #KDOT !
If anyone needs it:
class Page {
private $TEMPLATE_PATH = '/application/templates/';
private $VIEW_PATH = '/application/views/';
protected $header;
protected $footer;
protected $body;
public function __construct($header_file, $body_file, $footer_file) {
$this->header = $this->TEMPLATE_PATH . $header_file;
$this->body = $this->VIEW_PATH . $body_file;
$this->footer = $this->TEMPLATE_PATH . $footer_file;
}
public function render(){
$page = [$this->header, $this->body, $this->footer];
foreach($page as $file) {
require_once($file);
}
}
}
and:
$route->add('/', function() {
$page = new Page('header.php', 'home.php', 'footer.php');
$page->render();
});

What's the right method to divide and integrate a PHP script inside another one?

I just started coding PHP, I know how to include PHP however I encountered difficulties in this case.
I have a LAMP server, in the root folder I installed my own framework as below (folders are in capital letters).
index.php
page.php
INCLUDES
- classes.php
- skins.php
- flow_init.php
- flow_head.php
- flow_body.php
SOURCES
- page1.php
- page2.php
...
THEME_HTML
- wrapper.html
VIEWS
- page1.html
- page2.html
...
wrapper.html is created into index.php
<?php // index.php
$skin = new skin('wrapper');
echo $skin->make();
This is my skins.php file
<?php // INCLUDES/skins.php
class skin {
var $filename;
public function __construct($filename) {
$this->filename = $filename;
}
public function mk($filename) {
$this->filename = $filename;
return $this->make();
}
public function make() {
global $CONF;
$file = sprintf('./'.$CONF['theme_path'].'/'.$CONF['theme_name'].'/html/%s.html', $this->filename);
$fh_skin = fopen($file, 'r');
$skin = #fread($fh_skin, filesize($file));
fclose($fh_skin);
return $this->parse($skin);
}
private function parse($skin) {
global $TMPL, $LNG;
$skin = preg_replace_callback('/{\$lng->(.+?)}/i', create_function('$matches', 'global $LNG; return $LNG[$matches[1]];'), $skin);
$skin = preg_replace_callback('/{\$([a-zA-Z0-9_]+)}/', create_function('$matches', 'global $TMPL; return (isset($TMPL[$matches[1]])?$TMPL[$matches[1]]:"");'), $skin);
return $skin;
}
}
?>
Each page of VIEWS is created inside SOURCES and page.php echo it.
Script to integrate
Everything works fine, but now I need to integrate this script between the wrapper (where the head tag is) and one view (where the content is)
<?php
session_start();
require_once('admin/plugins/flow-flow/ff-injector.php');
$injector = new FFInjector();
?>
<!DOCTYPE html>
<html lang="en-US">
<head><?php echo $injector->head(true,true); ?>
</head>
<body>
<table width="100%">
<tr>
<td style="width: 300px;vertical-align: top">
<?php
$stream_id = isset($_REQUEST['stream']) ? $_REQUEST['stream'] : 1;
$injector->stream($stream_id);
?>
</td>
</tr>
</table>
</body>
</html>
For the purpose I tried to create some templates:
<?PHP // index.php
$TMPL['flow_init'] = include './includes/flow_init.php';
$TMPL['flow_head'] = include './includes/flow_head.php';
<?PHP // SOURCES/page1.php
$TMPL['flow_body'] = include './includes/flow_body.php';
Where my included files are set as below
<?PHP // flow_init.php
session_start();
require_once('admin/plugins/flow-flow/ff-injector.php');
$injector = new FFInjector();
?>
<?PHP // flow_head.php
echo $injector->head(true,true);
?>
<?PHP // flow_body.php
$stream_id = isset($_REQUEST['stream']) ? $_REQUEST['stream'] : 1;
$injector->stream($stream_id);
?>
What I would expect to achieve
I tried to include flow_init and flow_head on my wrapper, like this:
// THEME_HTML/wrapper.html
{$flow_init}
<!DOCTYPE html>
<html lang="en">
<head>
{$flow_head}
</head>
<body>
<div id="content" class="wrapper">
{$content}
</div>
</body>
</html>
And flow_body into my content
// THEME_HTML/VIEWS/page1.html
<div class="row-body{$content_class}">
<div class="body-content">
<div class="nine columns" id="main-content">
{$flow_body}
</div>
<div class="three columns">
{$sidebar}
</div>
</div>
</div>
The results is a blank page, however if I include all the 3 templates together in the index.php it works, so I think it's not a source path problem.
What's the right method to divide a PHP script and make it executable?
You need to learn PSR-4 autoloading and how to use Composer if you want to start including files within files. This will make it much easier than having to use require_once everywhere you wish to have a file included.
If you're talking about view templating, Don't Reinvent The Wheel, unless you want to learn more about wheels. The two best templating engines that I've used are Laravel's Blade and Symfony's Twig. You can also try out the League of PHP Developer's templating engine, which only uses raw PHP.

Autoload a view on every page with codeigniter

So I have my views split up basically between three (3) files:
-- Header file
$this->load->view('templates/header', $data);
-- Main Body file
$this->load->view('login_view', $data);
-- Footer file
$this->load->view('templates/footer', $data);
Now I just recently started building, but I've noticed it's really annoying to retype the header and footer on every controller to tell it to load. Is there a way to automatically load the header and footer view on every request?
I found an article long time ago, but i can't seem to find it now, basically the author, (which i forgot) override the showing of output. this method of output will access your views regarding the given controller/method and will try to search in your views directory automatically.
Use at your own risk
Application/core/MY_COntroller.php
----------------------------------------------------------------------------
class MY_Controller Extends CI_Controller
{
protected $layout_view = 'layouts/application'; // default
protected $content_view =''; //data
protected $view_data = array(); //data to be passed
public function __construct()
{
parent::__construct();
}
public function _output($output)
{
if($this->content_view !== FALSE && empty($this->content_view)) $this->content_view = $this->router->class . '/' . $this->router->method;
$yield = file_exists(APPPATH . 'views/' . $this->content_view . EXT) ? $this->load->view($this->content_view, $this->view_data, TRUE) : FALSE ;
if($this->layout_view)
{
$html = $this->load->view($this->layout_view, array('yield' => $yield), TRUE);
echo $html;
}
}
}
Application/views/layouts/layout.php
----------------------------------------------------------------------------
<html>
<head>
<title>master layout</title>
</head>
<body>
<!-- this variable yeild is important-->
<div><?=$yield;?></div>
</body>
</html>
This is what i use to create my template. Basically you need a directory structure as follows.
+Views
|+layouts
||-layout.php
the layout.php will serve as your master template
How to use?
extend the controller
class User Extends MY_Controller
{
public function create_user()
{
//code here
}
public function delete_user()
{
//use a different master template
$this->layout_view = 'second_master_layout';
}
public function show_user()
{
//pass the data to the view page
$this->view_data['users'] = $users_from_db;
}
}
Just create directory in your views and name it with the controller name i.e user then inside it add a file you named your method i.e create_user
So now your Directory structure would be
+Views
| +layouts
| |-layout.php
| |-second_master_layout.php
| +user
| |-create_user.php
Just Edit the code to give you a dynamic header or footer
Here is the simple example which i always do with my CI project.
Pass the body part as a $main variable on controller's function
function test(){
$data['main']='pages/about_us'; // this is the view file which you want to load
$data['something']='some data';// your other data which you may need on view
$this->load->view('index',$data);
}
now on the view load the $main variable
<html lang="en">
<head>
</head>
<body>
<div id="container">
<?php $this->load->view('includes/header');?>
<div id="body">
<?$this->load->view($main);?>
</div>
<?php $this->load->view('includes/footer');?>
</div>
</body>
</html>
In this way you can always use index.php for your all the functions just value of $main will be different.
Happy codeing
Using MY_Controller:
class MY_Controller extends CI_Controller {
public $template_dir;
public $header;
public $footer;
public function __construct() {
parent::__construct();
$template_dir = 'templates'; // your template directory
$header = 'header';
$footer = 'footer';
$this->template_dir = $template_dir;
$this->header = $header;
$this->footer = $footer;
}
function load_views ($main, $data = [], $include_temps = true) {
if ($include_temps = true) {
$this->load->view('$this->template_dir.'/'.$this->header);
$this->load->view($main);
$this->load->view('$this->template_dir.'/'.$this->footer);
} else {
$this->load->view($main);
}
}
}
Then load it like: $this->load_views('login_view', $data);
You can do with library.
Create a new library file called template.php and write a function called load_template. In that function, use above code.
public function load_template($view_file_name,$data_array=array()) {
$ci = &get_instatnce();
$ci->load->view("header");
$ci->load->view($view_file_name,$data_array);
$ci->> load->view("footer");
}
You have to load this library in autoload file in config folder. so you don't want to load in all controller.
You can call
$this->template->load_template("index",$data_array);
If you want to pass date to view file, then you can send via $data_array
There is an article on this topic on ellislab forums. Please take a look. It may help you.
http://ellislab.com/forums/viewthread/86991/
Alternative way: Load your header and footer views inside the concern body view file. This way you can have batter control over files you want to include in case you have multiple headers and footer files for different purposes. Sample code shown below.
<html lang="en">
<head>
</head>
<body>
<div id="container">
<?php $this->load->view('header');?>
<div id="body">
body
</div>
<?php $this->load->view('footer');?>
</div>
</body>
</html>

Get correct url / page to load in simple MVC

I´m making a "very" simple MVC framework in order to learn, however I have trouble getting other pages than the index page to show. In views folder I have 2 files one index.php and one register.php that I´m trying on.
I have tried various ways but can´t get my head around it. I know it is probably best to put different controller classes in different files and maybe a loader controller page but I´m a beginner with php so would like to make it as simple as possible for me...
Any help appriciated!
I have a index.php as a landing file in the root folder to bind everything together:
<?php
/* index.php
*
*/
require_once 'model/load.php';
require_once 'controller/main.php';
new mainController();
In the controller folder i have a file called main.php:
<?php
/* controller/main.php
*
*/
class mainController
{
public $load;
public function __construct()
{
$urlValues = $_SERVER['REQUEST_URI'];
$this->urlValues = $_GET;
//index page
if ($this->urlValues['controller'] == "") {
$indexPage = array("key" => "Hello");
$this->load = new load();
$this->load->view('index.php', $indexPage);
}
//register page
if ($this->urlValues['controller'] == "register.php") {
$registerPage = array("key" => "Register");
$this->load = new load();
$this->load->view('register.php', $registerPage);
}
}
}
And then I have a file called load.php in the model folder:
<?php
/* model/load.php
*
*/
class load
{
/* This function takes parameter
* $file_name and match with file in views.
*/
function view($file_name, $data = null)
{
if (is_readable('views/' . $file_name)) {
if (is_array($data)) {
extract($data);
}
require 'views/' . $file_name;
} else {
echo $this->file;
die ('404 Not Found');
}
}
}
In your mainController class you don't have property with the name urlValues, but you use it: $this->urlValues = $_GET;. And what is more you have local variable with the same name, that you don't use: $urlValues = $_SERVER['REQUEST_URI'];
And how you URL for register.php looks like?

How to call a function inside yii framework controller from core php file?

I am working in yii framework.I am getting stuck at a point where I have to call a function inside controller in yii framework from core php file. Actually I am going to create html
snapshot.
my folder structure is
seoPravin--
--protected
--modules
--kp
--Dnycontentcategoriescontroller.php
--DnycontentvisitstatController.php
--themes
--start.php (This is my customized file)
--index.php
1) Code of start.php file :--
<!DOCTYPE HTML>
<html>
<head>
<?php
if (!empty($_REQUEST['_escaped_fragment_']))
{
$yii=dirname(__FILE__).'/yii_1.8/framework/yii.php';
require_once($yii);
$escapeFragment=$_REQUEST['_escaped_fragment_'];
$arr=explode('/',$escapeFragment);
include 'protected/components/Controller.php';
include 'protected/modules/'.$arr[0].'/controllers/'.$arr[1].'Controller.php';
echo DnycontentcategoriesController::actiongetDnyContent(); //gettting error at this point
?>
</head>
<body>
<?php
//echo "<br> ".$obj->actiongetDnyContent();
}
?>
</body>
</html>
2) yii side controller function : This function work for normal but when I am calling using escaped_fragment it gives error
public static function actiongetDnyContent()
{
if (!empty($_REQUEST['_escaped_fragment_']))//code inside if statement not working
{
$escapedFragment=$_REQUEST['_escaped_fragment_'];
$arr=explode('/',$escapedFragment);
$contentTitleId=end($arr);
$model = new Dnycontentvisitstat(); //Error got at this line
}
else //Below code is working properly
{
$dependency = new CDbCacheDependency('SELECT MAX(createDateTime) FROM dnycontent');
$content = new Dnycontent();
$content->contentTitleId = $_GET['contentTitleId'];
$content = $content->cache(2592000,$dependency)->getContent();
$userId=105;
$ipAddress=Yii::app()->request->userHostAddress;
echo "{\"contents\":[".CJSON::encode($content)."]} ";
$model = new Dnycontentvisitstat();
$model->save($_GET['contentTitleId'], $userId, $ipAddress);
}
}
error:
Fatal error: Class 'Dnycontentvisitstat' not found in
C:\wamp\www\seoPravin\protected\modules\KnowledgePortal\controllers\DnycontentcategoriesController.php
on line 289
code is working for normal url but not working for _esaped_fragment
It is a very bad practice but you can do a HTTP self request, like this:
include("http://{$_SERVER['HTTP_HOST']}/path/?r=controller/action&_param={$_GET['param']}");
Check http://www.php.net/manual/en/function.include.php to see how to enable HTTP includes.

Categories