This is one of my controller:
class MediaController extends BaseController {
private $js_files = array(), $css_files = array();
/** Media specific function **/
static function base_uri(){
return sprintf(
"%s://%s%s",
isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
$_SERVER['HTTP_HOST'],
$_SERVER['REQUEST_URI']
);
}
function AddJquery($version = null) {
if($version === null) $version = 'custom';
$js_files[] = '<script src="assets/js/jquery/jquery.' . $version . '.js"></script>';
}
function AddJS($name, $minified = true) {
$js_base_uri = base_uri() . "assets/js/";
$js_files[] = $js_base_uri . ($minified ? '/min/' : '') . $name . ($minified ? '.min' : '') . '.js';
}
/** Page specific function **/
public function index_page() {
if(!empty($js_files)) $js_files = array();
if(!empty($css_files)) $css_files = array();
AddJquery();
AddJS('mainscript');
$data = array(
'js_files' => $js_files
);
return View::make('homepage', $data);
}
}
?>
When I access my main page with Route::get('/', 'MediaController#index_page');
in routes.php, in the index_page() it cannot access AddJquery() method.
Anyone can tell me why? Thanks.
Related
I have the function displayName in php that returns a string like this:
"${name} <i class=\"fa fa-check-circle\" style=\"font-size:22px;color:green\"/>"
public function getDisplayName()
{
/** #var Module $module */
$module = Yii::$app->getModule('user');
if ($module->displayNameCallback !== null) {
return call_user_func($module->displayNameCallback, $this);
}
$name = '';
$format = Yii::$app->settings->get('displayNameFormat');
if ($this->profile !== null && $format == '{profile.firstname} {profile.lastname}') {
$name = $this->profile->firstname . ' ' . $this->profile->lastname;
if (($this->profile->user_id == 1)){
$check_mark = '<i class="fa fa-check-circle" style="font-size:22px;color:green"/>';
}
else{
$check_mark = '';
}
}
// Return always username as fallback
if ($name == '' || $name == ' ') {
return $this->username;
}
return $name . ' '. $check_mark;
}
I call that function in my component like this:
public function run() {
return $this->render('containerProfileHeader', [ 'title' => $this->title, ]);
}
<h1 class="<?= $classPrefix ?>"><?= Html::encode($title) ?></h1>
public function init() {
parent::init();
$this->title = $this->container->getDisplayName();
}
The expectation was having the string returned by getDisplayName() rendered in the html as is but instead I've got this:
Issue resolved from
<?= Yii::$app->formatter->asHtml($title); ?>
Used
Yii::$app->formatter->asHtml instead of Html::encode
You should try echo() functions in the return function. I hope it will work.
I have a Joomla Module it will produce an error code with php 8.0.1 on wampserver on helper.php line 121 "Error Code: Non-static method modSidePanelHelper::getModuleById() cannot be called statically". This is helper.php
<?php
// no direct access
defined('_JEXEC') or die;
require_once JPATH_SITE . '/components/com_content/helpers/route.php';
if (!class_exists('LofPanelGroupBase')) {
require_once(dirname(__FILE__) . '/libs/group_base.php');
}
abstract class modSidePanelHelper {
/**
* get list articles
*/
public static function getList($params) {
if ($params->get('enable_cache')) {
$cache = JFactory::getCache('mod_sidepanel_jt1');
$cache->setCaching(true);
$cache->setLifeTime($params->get('cache_time', 15) * 60);
return $cache->get(array('modSidePanelHelper', 'getGroupObject'), array($params));
} else {
return self::getGroupObject($params);
}
}
/**
* get list articles
*/
public static function getGroupObject($params) {
$group = $params->get('group', 'file');
$file = dirname(__FILE__) .'/libs/groups/'. strtolower($group) . '/' . strtolower($group) . '.php';
if (file_exists($file)) {
require_once($file);
$className = 'SidePanelGroup' . ucfirst($group);
if (class_exists($className)) {
$object = new $className($group);
$object->setCurrentPath(dirname(__FILE__) .'/libs/groups/'. strtolower($group) . '/');
}
}
if ($object) {
return $object->getListByParameters($params);
} else {
return array();
}
}
/**
* load css - javascript file.
*
* #param JParameter $params;
* #param JModule $module
* #return void.
*/
public static function loadMediaFiles($params, $module, $theme='') {
$mainframe = JFactory::getApplication();
// if the verion is equal 1.6.x
JHTML::script('modules/' . $module->module . '/assets/script.js');
if ($theme && $theme != -1) {
$tPath = JPATH_BASE .'/templates/'. $mainframe->getTemplate() .'/html/'. $module->module . '/' . $theme .'/assets/style.css';
if (file_exists($tPath)) {
JHTML::stylesheet('templates/' . $mainframe->getTemplate() . '/html/' . $module->module . '/' . $theme . '/assets/style.css');
} else {
JHTML::stylesheet('modules/' . $module->module . '/tmpl/' . $theme . '/assets/style.css');
}
} else {
JHTML::stylesheet('modules/' . $module->module . '/assets/style.css');
}
}
/**
*
*/
public function renderItem(&$row, $params, $layout='_item') {
$mainframe = JFactory::getApplication();
$theme = $params->get('theme');
$tPath = JPATH_BASE .'/templates/'. $mainframe->getTemplate() .'/html/mod_sidepanel_jt1/'. $theme . '/' . $layout . '.php';
$bPath = JPATH_BASE .'/modules/mod_sidepanel_jt1/tmpl/'. $theme . '/' . $layout . '.php';
if (file_exists($tPath)) {
require($tPath);
} elseif (file_exists($bPath)) {
require($bPath);
}
}
/**
* load theme
*/
public static function getLayoutByTheme($module, $group, $theme= '') {
$mainframe = JFactory::getApplication();
// Build the template and base path for the layout
$tPath = JPATH_BASE .'/templates/'. $mainframe->getTemplate() .'/html/'. $module->module . '/' . $theme .'/default.php';
$bPath = JPATH_BASE .'/modules/'. $module->module .'/tmpl/'. $theme .'/default.php';
// If the template has a layout override use it
if (file_exists($tPath)) {
return $tPath;
} elseif (file_exists($bPath)) {
return $bPath;
}
}
public static function getModulesEnable($params) {
$enableModules = array();
for ($i = 0; $i <= 6; $i++) {
$module = $params->get('file' . $i);
if($module){
if (intval($module->enable) == 1) {
$enableModules[] = self::getModuleById($module->image);
}
}
}
return $enableModules;
}
private function getModuleById($id) {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('module, title');
$query->from('#__modules');
$query->where('published=1 AND client_id=0 AND id=' . $db->quote($id));
$db->setQuery($query);
return $db->loadObject();
}
static function getReturnURL($params, $type) {
$app = JFactory::getApplication();
$router = $app->getRouter();
$url = null;
if ($itemid = $params->get($type)) {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('link'));
$query->from($db->quoteName('#__menu'));
$query->where($db->quoteName('published') . '=1');
$query->where($db->quoteName('id') . '=' . $db->quote($itemid));
$db->setQuery($query);
if ($link = $db->loadResult()) {
if ($router->getMode() == JROUTER_MODE_SEF) {
$url = 'index.php?Itemid=' . $itemid;
} else {
$url = $link . '&Itemid=' . $itemid;
}
}
}
if (!$url) {
// stay on the same page
$uri = clone JFactory::getURI();
$vars = $router->parse($uri);
unset($vars['lang']);
if ($router->getMode() == JROUTER_MODE_SEF) {
if (isset($vars['Itemid'])) {
$itemid = $vars['Itemid'];
$menu = $app->getMenu();
$item = $menu->getItem($itemid);
unset($vars['Itemid']);
if (isset($item) && $vars == $item->query) {
$url = 'index.php?Itemid=' . $itemid;
} else {
$url = 'index.php?' . JURI::buildQuery($vars) . '&Itemid=' . $itemid;
}
} else {
$url = 'index.php?' . JURI::buildQuery($vars);
}
} else {
$url = 'index.php?' . JURI::buildQuery($vars);
}
}
return base64_encode($url);
}
}
line 121 is like this: $enableModules[] = self::getModuleById($module->image);
the self::getModuleById seems deprecated on php 8. Changing that line like this
$enableModules[] = (new modSidePanelHelper)->getModuleById($module->image);
causes another error code like this
Error Code: Cannot instantiate abstract class modSidePanelHelper
any suggestion? Thanks in advance
You have an abstract class:
abstract class modSidePanelHelper {
public static function getList($params) {
// ...
}
public static function getGroupObject($params) {
// ...
}
public static function loadMediaFiles($params, $module, $theme='') {
// ...
}
public function renderItem(&$row, $params, $layout='_item') {
// ...
}
public static function getLayoutByTheme($module, $group, $theme= '') {
// ...
}
public static function getModulesEnable($params) {
// ...
}
private function getModuleById($id) {
// ...
}
static function getReturnURL($params, $type) {
// ...
}
}
The only non-static function is getModuleById, which cannot be called from a static context of this class directly. You either have to create a new concrete class and call its instance then or make this function static.
In this case, I understand that making this class abstract is for preventing calling the constructor of this class, and this functionality is clearly only for static methods execution.
Then, replace:
private function getModuleById($id) {
// ...
}
with:
private static function getModuleById($id) {
// ...
}
I think you also have to do the same for the renderItem function, as long as it's not used here, it has to be executed in a static context if you need to execute it from some other place.
I want to make a 404 error page on this routing. How can this be done?
index.php
<?php
include 'route.php';
include 'control/about.php';
include 'control/home.php';
include 'control/contact.php';
$route = new route();
$route->add('/', function(){
echo 'Hello, this is home pageeees';
});
$route->add('/about', 'about');
$route->add('/contact', 'contact');
echo '<pre>';
print_r($route);
$route->submit();
?>
route.php
<?php
class route
{
private $_uri = array();
private $_method = array();
/**
*Builds a collection of internal URL's to look for
*#parameter type $uri
*/
public function add($uri, $method = null)
{
$this->_uri[] = '/' . trim($uri, '/');
if($method != null){
$this->_method[] = $method;
}
}
/**
*Makes the thing run!
*/
public function submit()
{
$uriGetParam = isset($_GET['uri'])? '/' . $_GET['uri'] : '/';
foreach ($this->_uri as $key => $value)
{
if(preg_match("#^$value$#",$uriGetParam))
{
if(is_string($this->_method[$key]))
{
$useMethod = $this->_method[$key];
new $useMethod();
}
else
{
call_user_func($this->_method[$key]);
}
}
}
}
}
?>
The regex in mind I would just add $route->add("/.+", function()...); after all your other routes.
Proof: https://3v4l.org/nk5PZ
But you could also program some logic which evaluates custom 404-Pages when not being able to find a correspondig route.
For example:
private $_notFound;
public function submit() {
$uriGetParam = isset($_GET['uri'])? '/' . $_GET['uri'] : '/';
$matched = false;
foreach ($this->_uri as $key => $value) {
if(preg_match("#^$value$#", $uriGetParam)) {
if(is_string($this->_method[$key])) {
$useMethod = $this->_method[$key];
new $useMethod();
} else {
call_user_func($this->_method[$key]);
}
$matched = true;
}
}
if(!$matched) {
if(isset($this->_notFound)) {
if(is_string($this->_notFound)) {
$action = $this->_notFound;
new $action();
} else {
call_user_func($this->_notFound);
}
}
}
}
public function notFound($callback) {
$this->_notFound = $callback;
}
Then you'll have to add the 404-action by $route->notFound(function... or "class");
I' am trying this from yesterday but can't find any resources to help me out. I' am building my own custom MVC for learning purpose. I' am stuck at a point where when a uri is not registered in the router class, it should throw in a 404 error message. I have tried a lot of tricks but nothing worked for me.
router.php
$router->get('', 'homeController#index', 'home');
$router->get('contact', 'contactController#index', 'contact');
$router->get('contact/locations', 'contactController#locations', 'contact');
controller.class.php
class Controller{
public function controller($ContollerMethod = null){
$contoller = explode('#', $ContollerMethod);
if( !empty($contoller[0]) ){
return $contoller[0];
}
}
public function method($ContollerMethod = null){
$method = explode('#', $ContollerMethod);
if( !empty($method[1]) ){
return $method[1];
}
}
public function view($view = null){
if( empty($view) ){
$view = 'page';
}
$file = site_path() . '/app/views/' . $view . '.php';
require_once($file);
}
public function render($ContollerMethod = null, $view = null, $data = array() ){
$controller = $this->controller($ContollerMethod);
$method = $this->method($ContollerMethod);
if( file_exists(site_path() . '/app/controllers/' . $controller . '.php') ){
require_once(site_path() . '/app/controllers/' . $controller . '.php');
if( !method_exists($controller, $method) ){
die('No method \'<em>' . $method . '</em>\' exists on Controller \'<em>' . $controller . '</em>\'');
}
$params = array();
call_user_func_array( [$controller, $method], $params );
$master = site_path() . '/app/views/master.php';
if( file_exists($master) ){
require_once( site_path() . '/app/views/master.php');
}
} else {
die('Controller \'<em>' . $controller . '</em>\' doesn\'t exists');
}
}
}
router.class.php
class Router extends Controller{
public function get($uri = null, $ContollerMethod = null, $view = null){
$permalink = get_permalink();
if( $permalink == $uri and strtolower($_SERVER['REQUEST_METHOD']) == 'get' ){
$this->render($ContollerMethod, $view);
}
}
public function post($uri = null, $ContollerMethod = null, $view = null){
$permalink = get_permalink();
if( $permalink == $uri and strtolower($_SERVER['REQUEST_METHOD']) == 'post' ){
}
}
public function ajax($uri = null, $ContollerMethod = null, $view = null){
$permalink = get_permalink();
if( $permalink == $uri and !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
}
}
}
$router = new Router;
Example:
contact, contact/locations are registed in the router.class.php so there is no problem and everything works fine, but the uri errorexample is not registered and it should show 404 error message from the views.
Please any help.
basic solution (but not the best) is add a return value (boolean) for Router::get(). The value returned is true if the route was handled and false if the route is not handled
router.php
// route handlers found
$founded = 0;
if( $router->get('', 'homeController#index', 'home') ){
$founded++;
}
if( $router->get('contact', 'contactController#index', 'contact') ){
$founded++;
}
if( $router->get('contact/locations', 'contactController#locations', 'contact') ){
$founded++;
}
// no handlers found... the route is handled by error controller
if( $founded <= 0 ){
$router->get('404', 'errorController#index', '404');
}
controller.class.php
class Router extends Controller{
/**
* Return true if a controller is found for handle the route
* #return boolean
*/
public function get($uri = null, $ContollerMethod = null, $view = null){
$permalink = get_permalink();
if( $permalink == $uri and strtolower($_SERVER['REQUEST_METHOD']) == 'get' ){
return $this->render($ContollerMethod, $view); // return true if a controller and a view are found
}
return false; // added this line
}
//.............
implement same loginc in controller::render()
controller.class.php
class Controller{
/**
* Return true if a controller is found
* #return boolean
*/
public function render($ContollerMethod = null, $view = null, $data = array() ){
$controller = $this->controller($ContollerMethod);
$method = $this->method($ContollerMethod);
if( file_exists(site_path() . '/app/controllers/' . $controller . '.php') ){
require_once(site_path() . '/app/controllers/' . $controller . '.php');
if( !method_exists($controller, $method) ){
die('No method \'<em>' . $method . '</em>\' exists on Controller \'<em>' . $controller . '</em>\'');
}
$params = array();
call_user_func_array( [$controller, $method], $params );
$master = site_path() . '/app/views/master.php';
if( file_exists($master) ){
require_once( site_path() . '/app/views/master.php');
}
return true; // add this line
} else {
die('Controller \'<em>' . $controller . '</em>\' doesn\'t exists');
}
return false; // add this line
}
// .....................................
now... my two cents
in your logic each router was called every time even if a controller is found. One optimization is stop this process if a controller was found, eg.:
router.php
if( $router->get('', 'homeController#index', 'home') ){
exit;
}
if( $router->get('contact', 'contactController#index', 'contact') ){
exit;
}
if( $router->get('contact/locations', 'contactController#locations', 'contact') ){
exit;
}
// no handlers found... the route is handled by error controller
$router->get('404', 'errorController#index', '404');
Side note: this a "spaghetti code" solution and sorry for my very bad english :(
I am using codeigniter. I need to get all variables from a language file to an array.Is it possible?
Is there any method available like as follows?
$a = $this->load->language('editor');
print_r($a);
I was tried $this->lang->language; But,This will return labels from another language files loaded.
$CI = & get_instance();
$arr = $CI->lang->language;
Or Use following library
Class My_language {
var $language = array();
/**
* List of loaded language files
*
* #var array
*/
var $is_loaded = array();
function __construct() {
log_message('debug', "Language Class Initialized");
}
function load($langfile = '', $idiom = '', $return = FALSE, $add_suffix = TRUE, $alt_path = '') {
$langfile = str_replace('.php', '', $langfile);
if ($add_suffix == TRUE) {
$langfile = str_replace('_lang.', '', $langfile) . '_lang';
}
$langfile .= '.php';
if (in_array($langfile, $this->is_loaded, TRUE)) {
return;
}
$config = & get_config();
if ($idiom == '') {
$deft_lang = (!isset($config['language'])) ? 'english' : $config['language'];
$idiom = ($deft_lang == '') ? 'english' : $deft_lang;
}
// Determine where the language file is and load it
if ($alt_path != '' && file_exists($alt_path . 'language/' . $idiom . '/' . $langfile)) {
include($alt_path . 'language/' . $idiom . '/' . $langfile);
} else {
$found = FALSE;
foreach (get_instance()->load->get_package_paths(TRUE) as $package_path) {
if (file_exists($package_path . 'language/' . $idiom . '/' . $langfile)) {
include($package_path . 'language/' . $idiom . '/' . $langfile);
$found = TRUE;
break;
}
}
if ($found !== TRUE) {
show_error('Unable to load the requested language file: language/' . $idiom . '/' . $langfile);
}
}
if (!isset($lang)) {
log_message('error', 'Language file contains no data: language/' . $idiom . '/' . $langfile);
return;
}
if ($return == TRUE) {
return $lang;
}
$this->is_loaded[] = $langfile;
$this->language = array();
$this->language = $lang;
return $this->language;
unset($lang);
log_message('debug', 'Language file loaded: language/' . $idiom . '/' . $langfile);
return TRUE;
}
}
Call like this
$this->load->library('my_language');
$arr = $this->my_language->load('demo');
print_r($arr);
I know this is quite an old question, but I just want to give my solution for this problem since no answers has done the trick for this problem. (tested on codeigniter 3)
$this->load->helper('language');
$foo = $this->lang->load('lang_file', 'english', true);
print_r($foo);
notice that the third parameter for load method determines whether to return the loaded array of translations. source: codeigniter 3 docs.
hope this helps
Yeah ofcourse its possible. You can do like this :
//load helper for language
$this->load->helper('language');
//test is the language file in english folder
$this->lang->load('test','english');
//fetch all the data in $var variable
$var=$this->lang->language;
//print $var
print_r($var);
$var will return the array. :)
If you want to return language file data in Array than you need to pass the third parameter in load function.
$this->lang->load('header','hindi',true) // filename,language,true