CodeIgniter website skeleton - php

I was coding PHP using controll based on adress and GET method with index.php?site=filename. Then i was including existing filename.php in content div. That was simply but effective. Also i has got notification div where i included file with data from database
I'm trying to get similar result in CodeIgniter
html
head
/head
body
div notification bar (always on top like Material)
div menu (slide from left also like Material)
div content (depended on controller and loaded view)
div footer (only /body /html)
/body
/html
by
public function __construct()
{
parent::__construct();
$this -> load -> view('notification ');
$this -> load -> view('menu ');
}
I want do send data from model to notification view but i can't do this in constructor. Also i dont want to load this same view in each controller's method. How should i do this? I dont expct ready solution, but some ideas, maybe pseudocode?
Or maybe this is only one solution like this? Loading all needed views in every methods? Really?
class news extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this -> load -> view('header');
}
public function index()
{
[...]//data from model
$this -> load -> view('notification',$Data);
$this -> load -> view('menu',$Permission);
$this -> load -> view('news',$Content);
}
[...]

I'm trying this (sorry for polish words):
controller
class uzytkownik extends CI_Controller
{
public function index()
{
$this -> load -> model('Uzytkownik_model');
$DaneLogo['Tytul'] = 'Dzie z życia';
$Dane = array(
'Naglowek' => $this -> load -> view('naglowek', NULL, TRUE),
'Logo' => $this -> load -> view('logo', $DaneLogo, TRUE),
'Lista' => $this -> Uzytkownik_model -> PobierzUzytkownikow(),
);
$this -> load -> view('uzytkownicy', $Dane);
}
view
echo $Naglowek;
echo $Tytul;
echo $Logo;
foreach ($Lista->result() as $Uzytkownik)
{
echo $Uzytkownik -> id.' ';
echo $Uzytkownik -> imie.' ';
echo $Uzytkownik -> nazwisko.'<br>';
}
working fine but...
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8"/>
</head>
<body>
<div id='logo' style='background-color: blue; wight: 100%; height: 40px;'>
<center> <!-- i want $Tytul HERE --></center>
</div>
Dzie z zycia<!-- NOT HERE -->1 Jan Kowalski<br>2 Adam Nowak<br>3 Alicja Marczak<br></div>
</body>

Related

CodeIgniter method Cannot get File Path Correctly

I parsed a html into Header, Sidebar, Content, Footer etc.. And main view put together.. It is working when I calling view from mycontroller/index but it isnt working when I calling view from mycontroller/method.. Pseude Code below;
Controller;
class welcome extends CI_Controller{
public function index(){
$data['content'] = "**main**_page";
$this->load->view('welcome_message',$data);
}
public function deneme(){
$data['content'] = "**another**_page";
$this->load->view('welcome_message',$data);
}
}
View;
<html>
<head>
<?php $this -> load -> view("includes/head_view");?>
</head>
<body>
<?php $this -> load -> view("includes/navbar_view");?>
<?php $this -> load -> view($content);?>
<?php $this -> load -> view("includes/footer_view"); ?>
</body>
</html>
Example Sub View
<img src="<?php base_url(); ?>assets/img/image1.jpg">
When I open below address, everything working fine, images loading
http://localhost/myproject
But When open below, images is not loading
http://localhost/myproject/welcome/deneme
I check the images url from Google Chrome> Page Source Code..
The link writing like that;
localhost/myproject/welcome/assets/img/image1.jpg
instead of
localhost/myproject/assets/img/image1.jpg
It's adding controller name to all links how can resolve it
Thank you
Where you define your base_url it says "URL to your CodeIgniter root. Typically this will be your base URL, WITH a trailing slash":
$config['base_url'] = 'http://localhost/myproject/';

Php OOP does not work

I have a problem. I writed OOP in php, but it does not work. It gives me blank result. I putted screenshots of my code and result of that code above. Please analyse these codes and help me, how I can solve it. By the way my php version is 5.3. I can upgrade or downgrade it if it is important. Thanks.
index.php
<?php include('class_library.php'); ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OOP ilk dersim)</title>
</head>
<body>
<?php
$phpders = new adam();
$padisah = new adam();
//----------
$phpders -> set_ad('NurlanXp 1');
$padisah -> set_ad('NurlanXp 2');
//------------
echo "PhpDersden gelen: ".$phpders -> get_ad;
echo "<br>Padisahdan gelen: ".$padisah -> get_ad;
?>
</body>
</html>
class_library.php
<?php
class adam{
var $ad;
function set_ad($yeni_ad){
$this -> ad = $yeni_ad;
}
function get_ad(){
return $this -> ad;
}
}
?>
index.php, class_library.php and the result of the code. Screenshots.
All documents in the same folder.
You seems using $padisah -> get_ad but your adam class doesn't have any getter metod so you have to use like
$padisah -> get_ad();
You can find working example on https://eval.in/591811
In Turkish: get_ad kısmının sonunda parantez açıp, kapatırsan sorun çözülür. Adam class'ının içerisinde getter metodu yok. Yukarıda verdiğim linkte sonundaki parantezle sorunun çözüldüğünü görebilirsin.
this is Your class:
<?php
class adam {
private $ad;
public function get_ad() {
return $this->ad;
}
public function set_ad($ad) {
$this->ad = $ad;
return $this;
}
}
and inside of code:
$phpders = new adam();
$padishah = new adam();
$phpders->set_ad('NurlanXP 1');
$padishah->set_ad('NurlanXP 2');
and usage of get_ad:
echo 'phpdersden gelen: '.$phpders->get_ad().'<br/>';
echo 'padishahdan gelen: '.$padishah->get_ad().'<br/>';
(After solving the issue mentioned by "num8er" - calling method with () ...)
Try to give an absolute include path
<?php include('/complete/path/to/class_library.php'); ?>
or set an appropriate include path set_include_path() before. You can use $_SERVER['DOCUMENT_ROOT'] as a base to build a path.

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>

Automated url request with php

Okay so I have been looking at developing my own custom CMS system for a specific market and I have been looking through a few frameworks and the problem that I have with them is that they don't automate routing. In laravel, if I remember correctly to respond to a url like this you would do something like this:
Route::get('/user', function()
{
return "This is a user";
});
This would essentially listen for a specific request. Now my idea to simplify this was to create an automated router. So what I did was setup an .htaccess file which took every request and directed it to index.php. It also took anything after the .com, so something like www.testsite.com/admin/pages/edit/5 and appended it as a get variable.
So in the example above I am passing four parameters of a single request:
admin - request path / used to signify a login check must be done before passing
them on to their request
pages - This would be the class or object
edit - This would be the method called from the class / object
5 - This would be the actual row of the record in the database being edited
So I developed a router class which looks something like this:
class router {
public $url;
public $protectedPaths = array('admin','users','client');
public function __construct() {
$this -> url = explode('/', $_GET['url']);
if($this -> url[0] == '') {
$this -> loadDefaultView();
} else {
// Check to ensure that the path is not protected
if(in_array($this -> url[0], $this -> protectedPaths)) {
// check to ensure user is logged in
if($_COOKIE['isLogged']) {
// This means that there is no action or model needed just a returned view
if($this -> url[2] == '') {
$this -> loadViewWithoutAction();
} else {
// we check to ensure there is a controller
if(file_exists(baseControllers .'controller.'. $this -> url[1] .'.php')) {
// require that controller and instantiate it
require baseControllers .'controller.'. $this -> url[1] .'.php';
$obj = new $this -> url[1];
// check to see if method exists
if(method_exists($obj, $this -> url[2])) {
if($_POST) {
$data = $_POST;
} else {
$data = array($this -> url[3]);
}
// run method if necessary
$data = call_user_func_array(array($obj, $this -> url[2]), $data);
$this -> loadAdminView( $data );
} else {
$this -> loadErrorView();
}
} else {
$this -> loadErrorView();
}
}
} else {
header("Location: /auth/form");
}
} else {
// we check to ensure there is a controller
if(file_exists(baseControllers .'controller.'. $this -> url[0] .'.php')) {
// require that controller and instantiate it
require baseControllers .'controller.'. $this -> url[0] .'.php';
$obj = new $this -> url[0];
// check to see if method exists
if(method_exists($obj, $this -> url[1])) {
// run method if necessary
$data = call_user_func_array(array($obj, $this -> url[1]), array($this -> url[2]));
$this -> loadPublicView( $data );
} else {
$this -> loadErrorView();
}
} else {
$this -> loadErrorView();
}
}
}
}
So I would use a number of different if else statements and perhaps a switch to differentiate between different requests etc. Finally my question, is this bad practice to auto load a class and run a method. From what I've seen in the frameworks, this is all manual and I'm no expert so I'm assuming there is probably a reason for that. In addition, I found little to anything about automating PHP requests in OOP on the web.
I'd really like to automate this but at the same time I also do not want to cause security concerns. Oh and for any forms or personal information being input by users everything would be post or ajax to protect against hacking the url.
Thanks for any advice or answers in advance!

Creating an object from a class in Codeigniter

The following codes are from http://d.hatena.ne.jp/dix3/20081002/1222899116 and codes are working well.
This is an example of using snoopy in codeigniter.
Q1. Am I correct to say that I can't use,
$this -> load -> library('snoopy')
since Snoopy.php does not create an object. And the example below is the way to do it?
If so, can you explain/direct me an tutorial or explanation of how to do it in details?
if ( ! class_exists('Snoopy'))
{
require_once(APPPATH.'libraries/Snoopy'.EXT);
}
Q2. Why do the author use
$to_specialchars=true
Is it needed for this?
Q3. Could you explain APPPATH and EXT.
APPPATH.'libraries/Snoopy'.EXT
I checked it in php.net but I could not find it. EXT must be extension, but can I use anywhere?
Thanks in advance.
I have a snoopy in application/library/Snoopy.php
I have application/library/Snoopy.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Scraping{
var $c;
function Scraping(){
if ( ! class_exists('Snoopy'))
{
require_once(APPPATH.'libraries/Snoopy'.EXT);
}
$this -> c = new Snoopy();
}
function getWebHtml($url="",$to_specialchars=true){
$this ->c -> fetch( $url );
$str = mb_convert_encoding( (string) $this -> c -> results,"UTF-8","auto");
return ($to_specialchars) ? htmlspecialchars($str , ENT_QUOTES , "UTF-8" ) : $str ;
}
function getWebText($url="",$to_specialchars=true){
$this -> c -> fetchtext( $url );
$str = mb_convert_encoding( (string) $this -> c -> results,"UTF-8","auto");
return ($to_specialchars) ? htmlspecialchars($str , ENT_QUOTES , "UTF-8" ) : $str ;
}
function getWebLinks($url=""){
$this -> c -> fetchlinks( $url );
return (array) $this-> c -> results ;
}
function getWebLinksText($url="",$delimiter="<br>"){
$arr = $this-> getWebLinks($url) ;
$ret ="";
foreach($arr as $k => $v){
$ret .= $v . $delimiter ;
}
return $ret;
}
} //endofclass
/* End of file Scraping.php */
/* Location: ./application/libraries/Scraping.php */
?>
I have a controller application/controller/mytasklist.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mytasklist extends Controller {
function Mytasklist()
{
parent :: Controller();
$this -> load -> helper( 'url' );
}
function index()
{
$data = "";
$this -> _SetTpl( $data );
}
function _SetTpl( $data )
{
$this -> load -> library("scraping");
$data["scraping"]["text"] = $this-> scraping -> getWebText("http://www.example.com/");
$data["scraping"]["html"] = $this-> scraping -> getWebHtml("http://www.example.com/");
$data["scraping"]["link"] = $this-> scraping -> getWebLinksText("http://www.example.com/","\n");
$tpl["page_title"] = "Welcome";
$tpl["main_content"] = $this -> load -> view( 'tasklist_view', $data , true );
$this -> load -> view( 'base_view', $tpl );
}
}
And I have a view, application/view/base_view.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="keywords" content="keyword here" />
<meta name="description" content="description here" />
<title><?php if(isset($page_title)){echo $page_title ;}?></title>
<?php if(isset($xajax_js)){echo $xajax_js ;}?>
<link href="http://127.0.0.1/ci_day4/css/mystyle.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="container">
<div id="rightblock">
<div id="content">
<?=$main_content?>
</div>
</div>
</div>
</body>
</html>
Q1. You can use:
$this->load->library('snoopy');
In your controllers. And create a new instance like so:
$snooper = new Snoopy();
The reason they are using:
if (!class_exists('Snoopy')) {
require_once(APPPATH.'libraries/Snoopy'.EXT);
}
Is because you will get a fatal error if you try and use $this->load->library(), since the loader class is not available in the library. You can call it in a controller is because your controllers extend the controller class, which extends the ci_base class, which extends the ci_loader class which is where the functionality to make calls like $this->load comes from. The Scraping class that you've shown here does not. If you dig down you'll see that the loader is basically using include_once to include whatever class, helper etc. you're trying to use.
Q2.
$to_specialchars = true
is being used in a couple the function declarations as parameters. Setting it '=true' is just setting a default, so you could can do this:
echo $scrappy->getWebHtml('http://example.com');
Which is identical to this:
echo $scrappy->getWebHtml('http://example.com', true);
If you look at the return statement of that function, you'll see they are $to_specialchars is being checked, and if it's true, then the output is run through the PHP function htmlspecialchars() first.
Q3. If you look at the root of your codeigniter project, in index.php you'll see EXT defined as:
define('EXT', '.'.pathinfo(__FILE__, PATHINFO_EXTENSION));
and APPATH:
if (is_dir($application_folder))
{
define('APPPATH', $application_folder.'/');
}
else
{
if ($application_folder == '')
{
$application_folder = 'application';
}
define('APPPATH', BASEPATH.$application_folder.'/');
}
So these are two constants being set at bootstrapping, so you can use them in your application, and if you were to ever change them, then it wouldn't instances like where you see it being used in the code you provided.
Please next time have one question per stackoverflow question :)
. This sample Scraping code was written based on using the library:
"Snoopy - the PHP net client ( snoopy.sourceforge.net )"
I tried to post it again. but I couldn't post with hyperlinks. sorry..
I'll answer to that in my site.(I'm a newbie stackoverflow.com :-( )
I think that I'll try to repost these answers after a few days .
( http://d.hatena.ne.jp/dix3/20091004 )

Categories