2
votes

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?

1

1 Answers

2
votes

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