How to set dynamic title to extended public variable with OOP? - php

I hope someone can help me. How can I best dynamically change page title, desc, or key vs..vs..by extending the original class? Here is what I have so far:
<?php
class siteGlobal
{
public $arr = array('title'=>'Page Default title','desc'=>'Page default description');
public function pageHeader()
{ ?>
<!doctype html><html>
<?php }
public function metaTags()
{ ?>
<head>
<meta charset="utf-8">
<title><?php echo $this->arr['title'];?></title>
<meta name="description" content="<?php echo $this->arr['desc'];?>">
<?php }
public function pageBody()
{ ?>
</head>
<body>
<?php }
public function pageFooter()
{ ?>
</body>
</html>
<?php }
} ?>
OTHER PAGE
require_once('siteGlobal.php');
class pageDetail extends siteGlobal
{
public function __construct()
{
$this->pageHeader();
$this->newMetas();
$this->startBody();
$this->sayfaBilgileri();
$this->pageFooter();
}
public function newMetas()
{
parent::metaTags();
}
public function sayfaBilgileri()
{
//HOW I can write a new title and description in this function to siteGlobal.php (public $metaInfo) ?>
<div style="width:640px; margin:0 auto;">
<h1>Page New Title</h1>
<h2>Page New Subtitle</h2>
<p>Lorem Ipsum, bla bla....</p>
</div>
<?php }
}
$writePage = new pageDetail(); ?>

You can try to create a method in the parent class say:
protected function setTitle($title){
$this->arr['title'] = $title;
}
and use it in the extended class this way:
parent::setTitle("My title");

Related

How to display the values of database table in CodeIgniter?

I am creating a sample image test where in I want to display all of the images in a database table in CodeIgniter. The question is, how will I able to display the values of the database table using CodeIgniter?
Here is the code of my model:
<?php
class Image_model extends CI_Model{
/*Sample test function for the image dropdown list*/
public function getImages()
{
$query = $this->db->select('main_image_url'));
$this->db->get('product_master');
return $query->result();
}
/*End sample test function*/
}
?>
Here is the code of my controller:
<?php
if(! defined('BASEPATH')) exit('No direct script access allowed');
class Sample_image_dropdown extends MX_Controller{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['main_view'] = 'sample_view/image_dropdown_view';
$this->load->view('sample_view/image_dropdown_view', $data);
}
public function display_all_images()
{
$this->load->model('sample_model/image_model');
$data['images'] = $this->image_model->getImages();
$data['main_view'] = "sample_view/image_dropdown_view";
$this->load->view('sample_view/image_dropdown_view', $data);
}
}
?>
Here is the code of my view:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>
<select name="" id="">
<option value="all">All Image</option>
<option value="with-image">With Image</option>
<option value="no-image">Without Image</option>
</select>
<input type="submit" value="Search">
</div>
<?php if (isset($images)):?>
<?php foreach ($images as $image):?>
<table>
<tr>
<td>
<th>
Images
</th>
</td>
</tr>
<tr>
<td>
<img src="<?php echo "$image->main_image_url";?>">
</td>
</tr>
</table>
<?php endforeach; ?>
<?php endif; ?>
</body>
</html>
You made a mistake in your model and in the controller, I mentioned the changes please note down and try,
Model File
class Image_model extends CI_Model{
/*Sample test function for the image dropdown list*/
public function getImages()
{
$query = $this->db->select('main_image_url');
$this->db->from('product_master');
$query = $this->db->get();
return $query->result();
}
/*End sample test function*/
}
Controller File,
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['main_view'] = 'sample_view/image_dropdown_view';
$this->display_all_images();
}
public function display_all_images()
{
$this->load->model('sample_model/image_model');
$data['images'] = $this->image_model->getImages();
$data['main_view'] = "sample_view/image_dropdown_view";
$this->load->view('sample_view/image_dropdown_view', $data);
}
I assume you are storing images in directory at the time of uploading at
uploads/abc.png
then you can get data from db (which you are already doing)
and in view :
<img src="echo dir_path./$image->main_image_url;" />
or if you are storing whole path in DB then :
<img src="echo $image->main_image_url;" />

Generate Web Page Using PHP Class

I am a university student experimenting with OOP and PHP. I was wanting to build up a page using a BuildPage class.
<?php
Class BuildPage {
private $title;
private $style;
private $head;
private $header;
private $page;
private $footer;
private $finalPage;
public function __construct($title, $style)
{
$this->title = $title;
$this->style = $style;
}
public function addHead()
{
$this->head = "
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>$this->title</title>
<link href='$this->style' rel='stylesheet' type='text/css'>
<link rel='stylesheet' href='style.css'>
</head>";
}
public function addToPage($partOfPage)
{
if(empty($this->page) || !isset($this->page))
{
$this->page = $partOfPage;
}
else {
$this->page .= "<br> " . $partOfPage;
}
}
public function addHeader($header)
{
$this->header = "<body><div class='container'><header> " . $header . "
</header>";
}
public function addFooter($footer)
{
$this->footer .= "<BR><footer> " . $footer . " </footer></div></body>
</html>";
}
public function getPage()
{
$this->finalPage = $this->head . $this->header . $this->page .
$this->footer;
return $this->finalPage;
}
}
?>
However, when I try to build the page using the functions, I cannot understand how to use PHP within the argument as below:
$buildPage->addToPage("
<!-- Here is our page's main content -->
<!-- Use function to display songs -->
<?php $music->displaySongs('xmlfiles/songs.xml'); ?>
");
If I escape the $ like \$ to try and make it a string, for some reason the becomes a comment in HTML. Is it possible for this approach to work at all?
Many Thanks
EDIT:
This is the index page below, i call the class at the bottom with an echo.
<?php
require_once('phpclasses/Connect.php');
require_once('phpclasses/BuildPage.php');
require_once('phpclasses/MusicIE.php');
$dbconnect = new Connect();
$music = new MusicIE();
$buildPage = new BuildPage("Music Website", "style.css");
$buildPage->addHead();
$buildPage->addHeader("
<!-- Here is the main header that is used accross all the pages of my
website
-->
<div class='PageHeading'>Available Music Listed Below:</div>
<nav>
<ul>
<li><a href='#'>Home</a></li>
<li><a href='#'>Register</a></li>
<li><a href='#'>Login</a></li>
</ul>
</nav>
<form>
<input type='search' name='q' placeholder='Search query'>
<input type='submit' value='Go!'>
</form>
");
$buildPage->addToPage("
<!-- Here is our page's main content -->
<!-- Use function to display songs -->
" . $music->displaySongs('xmlfiles/songs.xml'));
$buildPage->addFooter("
<!-- And here is my footer that is used across all the pages of our website
-->
<p>©Copyright 2017 by Kris Wilson. All rights reversed.</p>
");
echo $buildPage->getPage();
?>
Since you are passing a string to the function BuildPage::addToPage($partOfPage) you could try to pass the result of $music->displaySongs('xmlfiles/songs.xml') instead of the literal function call as a string. Like so:
$buildPage->addToPage("
<!-- Here is our page's main content -->
<!-- Use function to display songs -->
". $music->displaySongs('xmlfiles/songs.xml'));
Seems that your code is wrong on the addToPage function call. you should call it like this:
$buildPage->addToPage("
<!-- Here is our page's main content -->
<!-- Use function to display songs -->
".$music->displaySongs('xmlfiles/songs.xml'));
You should add the $music->displaySongs('xmlfiles/songs.xml') output to the end of the string.

Codeigniter displaying message

I dont know whats wrong with my code..
I am trying to display message from database, but i keep on getting error that $results are not defined.
Controller
public function getMessages()
{
$this->load->model('get_message');
$data['results']= $this->get_message->getMessage();
$this->load->view('home_view', $data);
}
Model
<?php
class get_message extends CI_Model{
function getMessage(){
$query = $this->db->query("SELECT * FROM messages");
return $query->result_array();
}
}
View
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Home</h1>
<h2>Welcome <?php echo $username; ?>!</h2>
<div id="Main">
<?php
foreach($results->result() as $row){
echo $row ->id;
echo $row ->user_username;
echo $row ->text;
echo $row ->posted_at;
echo "<br/>";
}
?>
</div>
Logout
</body>
</html>
EDIT: here is what my code looks like now
Controller
public function index()
{
$this->load->model('get_message');
$data['results']= $this->get_message->getMessage();
$this->load->view('home_view', $data);
}
Model
<?php
class get_message extends CI_Model{
function getMessage(){
$query = $this->db->query('SELECT * FROM messages');
return $query->result_array();
}
}
view
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Home</h1>
<div id="Main">
<?php
foreach($results as $row){
echo $row['id'];
echo $row['user_username'];
echo $row['text'];
echo $row['posted_at'];
echo "<br/>";
}
?>
</div>
</body>
</html>
This code works. if it doesn't you are doing something else wrong.
In the controller you send data as result
$data['result']= $this->get_message->getMessage();
Access in view like this:
foreach($result as $row){
}
You used as results in foreach instead of result
You are passing wrong element to the view.
$data['result']= $this->get_message->getMessage();
^
Should be
$data['results']= $this->get_message->getMessage();
^
Also in Model,
return $query->result();
Should be:
return $query;
And in view,
foreach($results as $row){
Should be
if ($results->num_rows()) { // IN CASE, THE RESULT HAS NO ROWS.
foreach($results->result() as $row) {
View :
Your code
foreach(**$results** as $row){
}
?>
change to
foreach(**$result** as $row){
}
?>
Try to get result in some other variable in your controller function -
public function getMessages()
{
$this->load->model('get_message');
$data['msgesult']= $this->get_message->getMessage();
$this->load->view('home_view', $data);
}
And then in view -
<div id="Main">
<?php
foreach($msgesult as $row){
echo $row['id'];
echo $row['user_username'];
echo $row['text'];
echo $row['posted_at'];
echo "<br/>";
}
?>
</div>
This should work.

Unable to insert data

I am a newbee to CodeIgniter and PHP. I am trying to insert data using a form and display it on the same view page using MVC pattern given by CodeIgniter. My View is:
<html>
<head>
<title>My Form</title>
</head>
<body>
<? echo form_open('books/input'); ?>
<? echo $id; ?>:
<? echo form_input('id'); ?>
</br>
<? echo $title; ?>:
<? echo form_input('title'); ?>
</br>
<? echo $body; ?>:
<? echo form_input('body'); ?>
</br>
<? echo form_submit('mysubmit','Submit!'); ?>
<? echo form_close(); ?>
</body>
</html>
and My Controller is:
<? class Books extends Controller{
function Books(){
parent::Controller();
}
function main(){
$this->load->model('books_model');
$data = $this->books_model->general();
//$this->load->view('books_main',$data);
}
function input(){
$this->load->helper('form');
$this->load->model('books_model');
$data = $this->books_model->general();
$this->load->view('books_input',$data);
}
} ?>
and My model is just returning the data entered by the user as:
<? class books_model extends Model{
function books_model(){
$this->load->helper('url');
}
function general(){
$data['id'] = 'id';
$data['title'] = 'title';
$data['body'] = 'body';
return $data;
}
} ?>
But when I try to access the form, it shows me an error quoting:
load->model('books_model'); $data = $this->books_model->general(); }
function input(){ $this->load->helper('form'); $this->load->model('books_model'); $data = $this->books_model->general();
$this->load->view('books_input',$data); } } ?>
404 Page Not Found
though I am accessing it with the same URL: localhost/CodeIgniter/index.php/books/input
How can I access this form and insert data successfully?
Every Class name should start with capital letter
like
class Books_model extends Model
and do type like this
$this->load->model('Books_model');
this could be the issue that you are getting "404 page not found".
Read some basic things that you have to follow from guide
http://ellislab.com/codeigniter/user-guide/general/models.html

CodeIgniter create a layout/template library

Before I begin I have to say that I have recently started learning CodeIgniter, so I'm sorry if I repeat this subject once again.
In procedural php I would do something like this
// the header.php
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="blah blah">
<title>My Site</title>
<link href="css/main.css" rel="stylesheet" media="screen">
<php? if($current_page == 'about.php'): ?>
<link href="css/secondary.css" rel="stylesheet" media="screen"> // or some embed styles (<stlye> ... </style>)
<?php endif; ?>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="js/main_script.js"></script>
<php? if($current_page == 'contact.php'): ?>
<script src="js/validation.js"></script>
<?php endif; ?>
</head>
<body>
// end of header.php
include('template/header.php');
<h1>Heading1</h1>
<p>Lorem Ipsum...</p>
include('template/footer.php');
//footer.php
//maybe some js and here
</body>
</html>
So I would like to do something similar and in CI. All pages/views will have the same main styles or scripts, but in some cases, some specific pages (like contact.php) may include, and only in these pages, some specific styles or scripts (like the validation.js).
I have found this video that shows how to create a template/layout library using CI, but I'm not quite sure how I can apply this functionality to work properly.
Put the bottom class in libraries/Layout.php (your app not the sys). In the autoload add the library:
$autoload['libraries'] = array('layout');
In your controller just write $this->layout->render();
The class will render the layout views/layouts/default.php and the view views/$controller.views/$method.php
In the default layout just put
<?php $this->load->view($view,$data); ?>
and thats it.
The code is
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Layout
{
public $data = array();
public $view = null;
public $viewFolder = null;
public $layoutsFodler = 'layouts';
public $layout = 'default';
var $obj;
function __construct()
{
$this->obj =& get_instance();
}
function setLayout($layout)
{
$this->layout = $layout;
}
function setLayoutFolder($layoutFolder)
{
$this->layoutsFodler = $layoutFolder;
}
function render()
{
$controller = $this->obj->router->fetch_class();
$method = $this->obj->router->fetch_method();
$viewFolder = !($this->viewFolder) ? $controller.'.views' : $this->viewFolder . '.views';
$view = !($this->view) ? $method : $this->view;
$loadedData = array();
$loadedData['view'] = $viewFolder.'/'.$view;
$loadedData['data'] = $this->data;
$layoutPath = '/'.$this->layoutsFodler.'/'.$this->layout;
$this->obj->load->view($layoutPath, $loadedData);
}
}
?>
I'm doing layout thing is like bellow.
I get content to data['content'] variable.
This is my controller.
class Article extends MY_Controller {
function __construct() {
parent::__construct();
$this->load->model('article_model');
}
public function index() {
$data['allArticles'] = $this->article_model->getAll();
$data['content'] = $this->load->view('article', $data, true);
$this->load->view('layout', $data);
}
This is my Layout.I'm using bootstrap layout.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Starter Template for Bootstrap</title>
<base href="<?php echo base_url(); ?>" />
<!-- Bootstrap core CSS -->
<link href="assets/bootstrap3.0.1/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<!-- <link href="starter-template.css" rel="stylesheet">-->
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"> Article Management System</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"> Admin <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>Add Article</li>
<li>All Article</li>
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container" style="margin-top: 80px;">
<?php echo $content; ?>
</div><!-- /.container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="assets/bootstrap3.0.1/js/bootstrap.min.js"></script>
</body>
</html>
This is my content view
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="page-header">
<h4>All Articles </h4>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach ($allArticles as $row) { ?>
<tr>
<td><?php echo $row->title; ?></td>
<td><?php echo substr($row->description,0,100); ?> ....</td>
<td></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
I have achieved the same thing with the following:
Put this code in your ./application/core/MY_Controller.php file:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller
{
protected $layout = 'layout/main';
public function __construct()
{
parent::__construct();
}
protected function render($file = NULL, &$viewData = array(), $layoutData = array())
{
if( !is_null($file) ) {
$data['content'] = $this->load->view($file, $viewData, TRUE);
$data['layout'] = $layoutData;
$this->load->view($this->layout, $data);
} else {
$this->load->view($this->layout, $viewData);
}
$viewData = array();
}
}
Create a layout folder inside ./application/views directory and then create your files with the entire html in it. Just put the <?php echo $content; ?> in that file where you want to put the dynamic content in it. Then in your controllers use $this->render(); and pass your file path and data. If you want to use a different layout for specific page just put the $this->layout = 'path_to_your_layout_file'; it will override the layout file to be used.
I have struggled with a similar problem not long ago. My solution to it was the following :
In your controller constructor create 2 arrays one of css files and one of js files and put in them the files common to all views.
And in each function in the controller add to them logic specific files.
For your example you'll have something like this :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->page_data = array();
$this->page_data['css']=array('main.css','bootstrap.css');
$this->page_data['js']=array('main.js','bootstrap.js');
}
public function about()
{
array_push($this->page_data['css'],'secondary.css');
$this->load->view('main_layout',$this->page_data)
}
public function contact()
{}
}
And in your view file you'll just iterate over the $css and $js array and include them one by one.
You can extend that easily to include header and footer templates by pushing them into the page_data array.
I ended up switching to doing all the templating on the client-side with Backbone and using Code Igniter as a REST API only but this technique gave me relatively clean code for what I needed.
5 Simple Steps to create CodeIgniter Template:
Step #1
Template.php # libraries
Step #2
Write following code
/* Start of file Template.php */
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Template {
var $template_data = array();
function set($name, $value)
{
$this->template_data[$name] = $value;
}
function load($template = '', $view = '' , $view_data = array(), $return = FALSE)
{
$this->CI =& get_instance();
$this->set('contents', $this->CI->load->view($view, $view_data, TRUE));
return $this->CI->load->view($template, $this->template_data, $return);
}
}
/* End of file Template.php */
/* Location: ./system/application/libraries/Template.php */
Step #3
open config/autoload.php
at line 55 replace
$autoload['libraries'] = array('database', 'session','encrypt');
with this code
$autoload['libraries'] = array('database', 'session','encrypt', 'template');
Step #4
On my controller call template as
//start
$this->template->load(TEMPLATE_NAME, VIEW_NAME , $this->data);
//end
Step #5
On views
create a file as custom_template.php
And place there following code--
//start
<?php $this->load->view('elements/header'); ?>
<div><?php echo $contents;?></div>
<?php $this->load->view('elements/footer'); ?>
//end
N.B. In views in elements folder create two files as header.php And footer.php
I use this, in older version of CodeIgniter and it works for version 3 as well.
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Layout
{
var $obj;
var $layout;
function Layout($layout = "layout_main")
{
$this->obj =& get_instance();
$this->layout = $layout;
}
function setLayout($layout)
{
$this->layout = $layout;
}
function view($view, $data=null, $return=false)
{
$loadedData = array();
$loadedData['content_for_layout'] = $this->obj->load->view($view,$data,true);
if($return)
{
$output = $this->obj->load->view($this->layout, $loadedData, true);
return $output;
}
else
{
$this->obj->load->view($this->layout, $loadedData, false);
}
}
}
?>
and to call this in the controller I use:
$this->layout->view('apps/apps', $data);

Categories