calling two classes functions to one sorted output - php

im surfing in index.php file and My code is this:
index.php =
require("template.php"); // the file with the template of the site
$title="Home";
$phead='';
$html->htmlhead();
$htmlside="";
$html->htmlside();
require("file2.php"); // a file with class $queans and function question()
$htmlbody = $queans->questions();
$html->htmlbody($htmlbody);
$htmlfoot="";
$html->htmlfoot();
template.php = contain class $html and all it functions that i wrote at the previous file. and the spific proflem with the htmlbody function:
//all the class plugin
//in this specific function i wrote
$html->htmlbody($htmlbody){
echo '<div id="s">'.$htmlbody.'</div>';
}
file2.php =
$queans = new ques;
class ques{
public function questions(){
echo 'test';
}
}
at the end it shows me the output of $queans->questions() before the output of function questions() and the output is like:
test
<div id="s">
</div>

In your file2.php you have to return 'test' instead of echoing it.

Related

Converting array key and values into single variables

I know that you can use extract() to achieve this however my circumstances are as followed:
I am building a very small basic MVC framework for personal projects and I have this in my controller:
public function index(){
$data = [
'title' => 'Welcome'
];
$this->view('pages/index', $data);
}
As you can see this passes the data array into the view and you can echo it like:
echo $data['title'];
But I want to echo it like echo $title; I know that extract() can do this but that means I have to manually put extract($data); at the top of every page which isnt the end of the world but I was just curious if there was a way it could be done automatically? I have tried to use extract by putting it inside the view function but that did not work. I have also tried to use extract by putting it in the header file that is required_once in index.php (thus making the header file a static header thats always required) but neither has worked so any advice would be great.
Here is the code for the view function as requested:
public function view($view, $data = []){
if(file_exists('../../views/'.$view.'.php')){
require_once '../../views/'.$view.'.php';
} else {
die('View does not exist');
}
}
Simple that is it ,use compact and extract function
index method
public function index(){
$title='Welcome';
$this->view('pages/index', compact('title'));
}
Wiew method
public function view($view, $data = []){
extract($data);
if(file_exists('../../views/'.$view.'.php')){
require_once '../../views/'.$view.'.php';
} else {
die('View does not exist');
}
}
In html
<h1> hello <?php echo $title; ?></h1>
Here is where I went wrong, I put extract in the view method before and it didn't work.
However the advice here was to put it in the view function and I now understand that I put the extract function after require_once '../../views/'.$view.'.php'; I just put extract before that line of code and it is now working!

cakephp call a controller function in view file

My method is
public function topmenu($parentsid=null){
$this->layout =false;
$category_tree = $this->Categorymaster->find('all',array('order'=>'Categorymaster.lft ASC','conditions'=>array('Categorymaster.parent_id'=>$parentsid)));
echo '<ul class="sub-menu" role="menu">';
foreach($category_tree as $parentval){
echo '<li>'.$parentval['Categorymaster']['name'].'</li>';
$id = $parentval['Categorymaster']['id'];
$haschild = $this->Categorymaster->children($id, true);
if (!empty($haschild)) {
$this->topmenu($id);
}
}
echo '</ul>';
$this->set(compact('category_tree'));
$this->render('topmenu');
}
I get output from controller
I am trying to use a foreach loop in my topmenu.ctp file but as cakephp
is mvc it gives error at the lines
$haschild = $this->Categorymaster->children($id, true);
if (!empty($haschild)) {
$this->topmenu($id);
}
so how can it use topmenu() method in .ctp file so that i can show it in my menu or any other alternative.
First of all its never a good practice to call controller method directly in ctp (view) file.
If you still want to do this, try to call like this:-
Controller name::(scope resolution operator) function name(parameters).
Note:-Make sure that your method is public.

PHP Vars From Included Bootstrap Not Showing Up in View

I have created my own little PHP framework for fun, however, I am having trouble passing variables from bootstrap to the views....
if I put an echo,print_r,var_dump my target variable in the bootstrap, the output is displayed in the browser before the tag... yet the target var in bootstrap.php is not available in the view, it is coming up as "" even though at the top of the page it is being output correctly....
Somethings I noticed from similar questions:
- The target variable is not being over written
- The include target path is correct and the file exists
- The file is only being included one time (include_once is only fired once)
Any ideas are greatly appreciated, I am pulling my hair out over here lol...
Source Code
https://gist.github.com/jeffreyroberts/f330ad4a164adda221aa
If you just want to display your site name, I think you can use a constant like that :
define('SITE_NAME', "Jeff's Site");
And then display it in your index.tpl :
<?php echo SITE_NAME; ?>
Or, you can send your variables to the view by extending a little bit your JLR_Core_Views :
class JLR_Core_Views
{
private $data;
public function loadView($templatePath, $data = array())
{
$this->data = $data;
$templatePath = JLR_ROOT . '/webroot/' . $templateName . '.tpl';
if(file_exists($templatePath)) {
// Yes, I know about the vuln here, this is just an example;
ob_start();
include_once $templatePath;
return ob_get_clean();
}
}
function __get($name)
{
return (isset($this->data[$name]))
? $this->data[$name]
: null;
}
}
Then, you can call your template like that :
$view = new JLR_Core_Views();
$view->loadView("index", array("sitename" => "Jeff's Site"));
And here is your index.tpl :
<?php echo $this->siteName; ?>
Below is another example of what you can do.
First, you create this class in order to store all the variables you want :
<?php
class JLR_Repository {
private static $data = array();
public function set($name, $value) {
self::$data[$name] = $value;
}
public function get($name) {
return (isset(self::$data[$name]))
? self::$data[$name]
: null;
}
}
?>
Then, when you want to store something in it :
JLR_Repository::set("sitename", "Jeff's Site");
And in your index.tpl :
<?php echo JLR_Repository::get("sitename"); ?>
try using the 'global' keyword - http://php.net/manual/en/language.variables.scope.php

How to include some php class to Joomla tmpls

I need to include some php code that must be repeated in many tmpls. How can I do this, may be as class including? And how can I write php file with my class in a right way? In other words I need something like
views/category/tpml/default.php
JLoader::register('MyClass', '/administrator/components/com_mycom/helpers/myclass.php');
$repeatedcode = new MyClass();
echo $resultstr;
views/article/tpml/default.php
JLoader::register('MyClass', '/administrator/components/com_mycom/helpers/myclass.php');
$repeatedcode = new MyClass();
echo $resultstr;
myclass.php
class MyClass {
// some code with string for echo in the end
$resultstr = ...
}
...
UPDATE: #Guilherme thank you! So now it's looking as
The file /mytemplate/html/com_content/article/default.php:
require_once '/administrator/components/com_mycom/helpers/myclass.php';
MyComHelper::myFunction($param);
$newstring = str_replace($find, $replace, $this->item->text);
echo $newstring;
The file administrator/components/com_mycom/helpers/myclass.php:
defined('_JEXEC') or die;
abstract class MyComHelper
{
public static function myFunction($param)
{
$db = &JFactory::getDBO();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('ua', 'ru')))
->from($db->quoteName('#__words'));
$db->setQuery($query);
$results = $db->loadAssocList();
$find = array();
$replace = array();
foreach ($results as $row) {
$find[] = $row['ua'];
$replace[] = $row['ru'];
}
return $find;
return $replace;
}
}
This script replaces every ua words with matched ru words that are stored in my database and it works if I add the script to tmpl directly. But in the case with including when I open a page with an article I see the blank page which contains only a heading and nothing else i.e. content isn't displayed. Maybe a problem with array?
After include the php function in your Helper, you can include it on the tmpl with the require_once
require_once JPATH_COMPONENT.'/helpers/mycom.php';
MycomHelper::myFunction($param);
MycomHelper is the class name of my Helper
com_mycom/helpers/helper.php
<?php
// no direct access
defined('_JEXEC') or die;
// Component Helper
jimport('joomla.application.component.helper');
class MycomHelper
{
public static function dosomething($var)
{
return "Helper say: ".$var;
}
}
In my tmpl of a com_content view (first lines)
components\com_content\views\article\tmpl\default.php
<?php
defined('_JEXEC') or die;
JHtml::addIncludePath(JPATH_COMPONENT . '/helpers');
if(!defined('DS')) { define('DS',DIRECTORY_SEPARATOR); }
require_once JPATH_ROOT.DS."components".DS."com_mycom".DS."helpers".DS."helper.php";
echo MycomHelper::dosomething("hello!!!");
And now, you can see the phrase "Helper say: hello!!!" in every article joomla

How do I use a controller within a controller?

I am using Kohana 3.2 and I am having problems calling the ouput of a controller in another controller.
What I want...
In some pages I have got a menu, and in others I don't. I want to use make use of the flexability of the HMVC request system. In the controller of a page I want to call another controller which is responsible for the creation of the menu.
What I have a the moment:
file menu.php:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Menu extends Controller
{
private $_model = null;
public function __construct(Request $request, Response $response)
{
parent::__construct($request, $response);
$this->_model = Model::factory('menu');
}
public function action_getMenu()
{
$content = array();
$content['menuItems'] = $this->_model->getMenuItems();
// Render and output.
$this->request->response = View::factory('blocks/menu', $content);
//echo '<pre>'; print_r($this->request->response->render()); echo '</pre>'; die();
}
}
somepage.php
public function action_index()
{
$this->template->title = 'someTitle';;
$contentData['pageTitle'] = 'someTitle';
$contentData['contentData'] = 'someData';
#include the menu
$menuBlock = Request::factory('menu/getMenu')->execute();
$menuData = array('menu' => $menuBlock);
$this->template->menu = View::factory('pages/menu')->set('menu',$menuData);
$this->template->content = View::factory('pages/somePage', $contentData);
$view = $this->response->body($this->template);
$this->response->body($view);
}
If I uncomment the following line in menu.php, I see the menu rendered:
//echo '<pre>'; print_r($this->request->response->render()); echo '</pre>'; die();
So I guess that part is alright. The problem is in the following line in somepage.php:
$menuBlock = Request::factory('menu/getMenu')->execute();
This gives me back a response object. Whatever I do, I do not get the output in $this->template->menu.
$this->template->menu = View::factory('pages/menu')->set('menu',$menuData);
What must I do to have $this->template->menu contain the view, so I can use it correctly?
I hope this all makes sense. This is the way I would like to do it, but maybe I am completely on the wrong track.
I would do it this way:
class Controller_Menu extends Controller
{
public function action_build()
{
// Load the menu view.
$view = View::factory('navigation/menu');
// Return view as response-
$this->response->body($view->render());
}
}
In your controller get the menu as follows:
// Make request and get response body.
$menu = Request::factory('menu/build')->execute()->body();
// e.g. assign menu to template sidebar.
$this->template->sidebar = Request:.factory('menu/build')->execute()->body();
I would not use the __construct method in your controllers. Use before() instead, this is sufficient for most of the problems (for example auth):
public function before()
{
// Call aprent before, must be done here.
parent::before();
// e.g. heck whether user is logged in.
if ( !Auth::instance()->logged_in() )
{
//Redirect if not logged in or something like this.
}
}
I found the answer to my problem in less than an hour after asking.
I just forgot to put it here.
In somePage.php change :
$menuBlock = Request::factory('menu/getMenu')->execute();
$menuData = array('menu' => $menuBlock);
$this->template->menu = View::factory('pages/menu')->set('menu',$menuData);
To:
$this->template->menu = Request::factory('menu/getMenuBlock')->execute()->body();
And in menu.php change:
$this->request->response = View::factory('blocks/menu', $content);
To:
$request = View::factory('blocks/menu', $content);
$this->response->body($request);
I hope this will help someone else.

Categories