Here, I see someone suggesting to extend the Zend\View\Helper\Escaper\AbstractHelper;, resulting in something like this:
namespace Photo\View\Helper;
use Zend\View\Helper\Escaper\AbstractHelper;
class Imghelper extends AbstractHelper
{
protected $_baseUrl = null;
protected $_exists = array();
public function __construct ()
{
$url = PUBLIC_PATH;
$root = '/' . trim($url, '/');
if ($root == "/")
{$root = "";}
$this->_baseUrl = $root . "/";
}
public function escape($value)
{
return $this->getEscaper()->escapeHtml($value);
}
public function __invoke($path, $params = array())
{
$plist = array();
$str = null;
$imgpath = $this->_baseUrl . ltrim($path);
if (!isset($this->_exists[$path]))
{$this->_exists[$path] = file_exists(realpath($imgpath));}
if (!isset($params['alt']))
{$params['alt'] = '';}
foreach ($params as $param => $value)
{$plist[] = $param . '="' . $this->escape($value) . '"';}
$str = " ".join(" ", $plist);
$p = ($this->_exists[$path]) ? $this->_baseUrl.ltrim($path,'/') : null;
if (isset($p))
{return '<img src="'.$p.'" '.$str.' />';}
}
}
However, when I try it in my codes, I get an Error
Strict Standards: Declaration of Application\View\Helper\Imghelper::__invoke() should be compatible with Zend\View\Helper\Escaper\AbstractHelper::__invoke($value, $recurse = 0) in ...
Is it ok to error the error message? Or is there any better ways to do this? Thanks!
I wouldn't recommend extending the Abstract Escape helper since you aren't writing an escape helper. Stick to your original plan and just extend Zend\View\Helper\AbstractHelper. You can then access the escape helpers via. $this->view->escapeHtml(), $this->view->escapeJs() and so on.
Related
I've been searching this problem for 2 days but no luck. I want to add custom methods to laravel carbon. I use the syntax below:
namespace App\Http\Controllers\Helpers;
use Carbon\CarbonInterface;
interface CarbonJalaliInterface extends CarbonInterface {
public function toJalaliDateTimeString($unitPrecision = 'second');
public function toJalaliDateString($unitPrecision = 'second');
}
abstract class CarbonJalali implements CarbonJalaliInterface {
public function toJalaliDateTimeString($unitPrecision = 'second') {
list($part1, $part2) = explode(' ', $this->rawFormat('Y-m-d '.static::getTimeFormatByPrecision($unitPrecision)));
list($year, $month, $day) = explode('-', $part1);
list($hour, $minute, $second) = explode(':', $part2);
$timestamp = mktime($hour, $minute, $second, $month, $day, $year);
include_once ('jdf.php');
$jalali_date = jdate("H:i:s - Y/m/d",$timestamp);
return $jalali_date;
}
public function toJalaliDateString($unitPrecision = 'second') {
$timezone = 0;
list($part1, $part2) = explode(' ', $this->rawFormat('Y-m-d'));
list($year, $month, $day) = explode('-', $part1);
$timestamp = mktime($month, $day, $year);
include_once ('jdf.php');
$jalali_date = jdate("Y/m/d",$timestamp);
return $jalali_date;
}
}
But i get the error:
Symfony\Component\Debug\Exception\FatalErrorException DateTimeInterface can't be implemented by user classes
I want to use it like this :
CarbonJalali::now()->toJalaliDateTimeString();
Any suggestions? Thanks.
What I Want to do
I want to convert URLs to tags like this:
あいうえおかきくけこhttp://localhostさしすせそたちつてと
↓
あいうえおかきくけこhttp://localhostさしすせそたちつてと
I want to use a custom Function in Model to do it.
What I did
I added this to my model:
class hogehoge extend Model {
public function convertUrlToLink($value)
{
// URLをaタグで囲む
$pattern = '/((?:https?|ftp):\/\/[-_.!~*\'()a-zA-Z0-9;\/?:#&=+$,%#]+)/';
$replace = '$1';
$text = preg_replace($pattern, $replace, $value);
return $text;
}
}
and called it like this:
Hogehoge::first(1)->text->convertUrlToLink()
But this gives an error:
Call to a member function convertUrlToLink() on string (View: /app/resources/views/club/show.blade.php)
How can I make custom Function in Model and use it in my templates?
You can access your attribute text directly in the model
class Hogehoge extend Model {
public function convertUrlToLink()
{
// URLをaタグで囲む
$pattern = '/((?:https?|ftp):\/\/[-_.!~*\'()a-zA-Z0-9;\/?:#&=+$,%#]+)/';
$replace = '$1';
$text = preg_replace($pattern, $replace, $this->text);
return $text;
}
}
Then you don't need it there
Hogehoge::first(1)->convertUrlToLink()
If it needs to be reusable, I would do a static method (that's only a preference)
public static function convertUrlToLink($value)
{
// URLをaタグで囲む
$pattern = '/((?:https?|ftp):\/\/[-_.!~*\'()a-zA-Z0-9;\/?:#&=+$,%#]+)/';
$replace = '$1';
$text = preg_replace($pattern, $replace, $value);
return $text;
}
Then you use it like this
Hogehoge::convertUrlToLink(Hogehoge::first(1)->text)
Hogehoge::convertUrlToLink(Hogehoge::first(1)->someAnotherText)
Basically, I have an admin (CMS) for my app. I have included menu and submenu setup, which are eventually populated on my nav section.
Name: User
URL: setup/user
Icon: fa fa-user
The problem is, if I add new menu (like above), I have to setup another route on web.php, like:
Route::resource('setup/user','UserController');
Well, there will be lots of menu to be created and my web.php is somehow messed up with lots of routes.
I followed this article and it gave me an idea, I tweaked it and created my own.
https://laracasts.com/discuss/channels/laravel/dynamically-calling-a-controller-method-in-laravel-5
Here's what I've done:
function wildcard($route, $controller, $verbs = ['get', 'post']) {
$stack = Route::getGroupStack();
$namespace = end($stack)['namespace'];
$controller = ucfirst(strtolower($route)).'Controller';
Route::match($verbs, rtrim($route, '/') . '/{method}', function($method, $params = null) use ($route, $namespace, $controller)
{
$controller = $namespace . '\\' . $controller;
$method = $controller . '#' . $method;
$params
? App::call($method, explode('/', $params))
: App::call($method);
});
}
wildcard('home',null);
My HomeController:
public function index()
{
return view('pages.common.dashboard');
}
But it doesn't display the view on my index method, just blank page. But it did get the method because I can dump from the method.
Maybe there's a better way on dynamic routing. Thanks.
Solution: You must return your App::call()
Route::match($verbs, rtrim($route, '/') . '/{method}', function($method, $params = null) use ($route, $namespace, $controller)
{
$controller = $namespace . '\\' . $controller;
$method = $controller . '#' . $method;
if($params){
// return the App::call
return App::call($method, explode('/', $params));
} else {
// return the App::call
return App::call($method);
}
});
I have build my own component in joomla and client wants now a friendly urls f.e
website.com/someplace/{product-id}-{product-name}. So i Build my own router like this.
function componentBuildRoute(&$query)
{
$segments = [];
if (isset($query['view'])) {
$segments[] = "szkolenie";
unset($query['view']);
}
if (isset($query['product_id'])) {
$productName = JFilterOutput::stringURLSafe(strtolower(getProductName($query['product_id'])));
$newName = $query['product_id'] . '-' . $productName;
$segments[] = $newName;
unset($query['product_id']);
}
return $segments;
}
and parse route function
function componentParseRoute($segments)
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
$item =& $menu->getActive();
$count = count($segments);
switch ($item->query['view']) {
case 'catalogue' : {
$view = 'training';
$id = $segments[1];
}
break;
}
$data = [
'view' => $view,
'product_id' => $id
];
return $data;
}
While on the end of buildroute function segments are ok I have exactly what I want that on the beginning of parse route I have something like
website.com/szkolenie/1-krakow <-- I dont know wtf is this krakow( I know it is city i Poland) but still where is it get from ? The getProductName function implementation is
function getProductName($productId)
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('#__component_training.id as id, #__component_product' . name)
->from($db->quoteName('#__component_training'))
->where('#__s4edu_product.product_id = ' . $productId)
->leftJoin('#__component_product ON
#__component_training.product_id=#__component_product.product_id');
$training = $db->loadObject();
return trim($training->name);
}
So taking all this into consideration I think that something is happening between the buildRoute and parseRoute, something what filters the $segment[1] variable, but how to disable that and why is it happening ?
P.S
Please do not send me to https://docs.joomla.org/Joomla_Routes_%26_SEF
I already know all the tutorials on joomla website which contains anything with sef.
P.S.S
It is built on joomla 3.7.0
You do not have a product named "krakow" ?
If not you can try to remove the $productName from the build function, just to check if this "krakow" is added automaticaly or it's from the getProductName() function.
Also i noticed that you have an error i guess in the function getProductName()
->where('#__s4edu_product.product_id = ' . $productId)
It's should be
->where('#__component_product.product_id = ' . $productId)
I have a problem with database select function, in my custom model. This is the code
class MY_Model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('inflector');
}
public function fetch($parameters = array(), $raw = FALSE)
{
$tablename = $this->getTableName();
$this->select_fields(FALSE == empty($parameters['fields']) ? $parameters['fields'] : FALSE);
unset($parameters['fields']);
if (FALSE == empty($parameters['limit'])) $limit = $parameters['limit'];
if (FALSE == empty($parameters['offset'])) $offset = $parameters['offset']; else $offset = 0;
unset($parameters['limit']);
unset($parameters['offset']);
if (FALSE == empty($limit))
{
$this->db->limit($limit, $offset);
}
$this->parseFilters($parameters);
$query = $this->db->get($tablename);
if ($query->num_rows() > 0)
{
if ($raw)
return $query;
$rows = $query->result();
$objects = array();
foreach ($rows as $row)
$objects[] = $this->hidrate($row);
return $objects;
}
else
{
return array();
}
}
protected function select_fields($fields)
{
if (TRUE == empty($fields))
{
$fields = "`" . $this->getTableName() . "`.*";
}
$this->db->select($fields);
}
public function fetchOne($parameters = array())
{
$parameters['limit'] = 1;
$list = $this->fetch($parameters);
if (FALSE == empty($list))
{
return reset($list);
}
else
{
return null;
}
}
Expecifict in $this->db->select($fields);
Fatal error: Call to a member function select() on a non-object
The model is a custom model and the applicacions model extends of this model. The question is why throws that error the database is correct.
I have a MY_loader create in codeginiter 1.7 and I try update to codeigniter 2
class MY_Loader extends CI_Loader
{
function model($model, $name = '', $db_conn = FALSE)
{
if (is_array($model))
{
foreach($model as $babe)
{
$this->model($babe);
}
return;
}
if ($model == '')
{
return;
}
if ( substr($model, -4) == '_dao' )
{
return parent::model('dao/' . $model, $name, $db_conn);
}
parent::model( 'dao/' . $model . '_dao', $model, $db_conn);
include_once APPPATH . '/models/' . $model . EXT;
}
}
I don't know how update this model to codeigniter 2 and I believe this Loader generates error with my MY_Model
I'll try troubleshooting why does db return as a non-object.
I'd remove all code and start with a simple select(), if that works, I'll start adding code gradually and see where it breaks.
everything seems to be in order but first you'll need to see if the basic functionality exists.
so
1)remove all code, see if a basic select() works, if it doesn't, troubleshoot further.
2)if it does, keep adding code and see what breaks the select() statement.
3)keep adding code until you spot the issue.