Joomla 2., 3. useful code cheatsheet



URL

// 绝对地址
JURI::root();
// 相对地址
JURI::base(true);

修改当前URL的参数

JUri::reset(); // 防止实例被干扰
$uri = JUri::getInstance();
$uri->setVar('order', $direction);
$url = $uri->toString();

获得POST & GET

$input = new JInput();
$input->get('Itemid', 0, 'int');
$input->get('cid', array(), 'array');

JObject转换成Array

JArrayHelper::fromObject($config);Array转换成Object:$obj = new JRegistry($dataConf);

JObject转换成PHP Code

$str = $c->toString('PHP', array('class' => 'JConfig', 'closingtag' => false));

文件写入

JFile::write($file, $str);

抛出异常

JError::raiseWarning(21, JText::_('WARNFS_ERR02'));

编辑器

$editor = JFactory::getEditor();
$editor->display(, , '100%;', '350', '75', '20', array('pagebreak'));

Log

jimport('joomla.log.log');
JLog::addLogger(array('text_file' => 'my-error-file.php'));
JLog::add('some error message');

Cache

$cache = JFactory::getCache('com_languages', '');
if (!$languages = $cache->get('languages'))
{
$cache->store($languages, 'languages');
}

Session

$session = JFactory::getSession();
$session->set($key, $value, $namespace);
$session->get($key, $defaultValue, $namespace);
$session->clear($key, $namespace);
$session->has($key, $namespace);

Profile Plugin是否已开启

JPluginHelper::isEnabled('user', 'profile');

得到configuration.php的值

$config = JFactory::getConfig();
$config->get('sitename');

动态添加用户

$user = new JUser;
$data = array(
'name' => 'systemwilliam',
'username' => 'systemwilliam',
'email' => 'systemwilliam@qq.com',
'password' => '123456',
'usertype' => 'deprecated',
'activation' => '',
'block' => 0,
// register group
'groups' => array(2)
);
$user->bind($data);
$user->save();
echo $user->id;

dump

$data = array(1,2,3);
echo JUtility::dump($data);

homepage识别

$app = JFactory::getApplication();
$isHome = $app->getMenu()->getActive()->home;

JS & CSS

$doc = JFactory::getDocument();
$doc->addStyleSheet(JUri::base().'/css/template_css.css');
$doc->addScript(JUri::base().'/js/modernizr.js');

分页

$limit = 10;
$total = 100;
$start = 0;
jimport('joomla.html.pagination');
$pagination = new JPagination($total, $start, $limit);
$pagination->getPagesLinks();

组件参数设置与取值方法

设置参数:administrator/com_xxx/config.xml
获取参数:$cparams =JComponentHelper::getParams('com_xxx');

MENU参数设置与取值方法

设置参数:com_xxx/views/xxx/tmpl/default.xml
获取参数:JFactory::getApplication()->getParams();

任意文本支持内容插件(激活onContentPrepare事件)

require_once(JPATH_ROOT.DS.'components'.DS.'com_content'.DS.'models'.DS.'articles.php');
$model = new ContentModelArticles();
$items = $model->getItems();
$article = array_pop($items);
JPluginHelper::importPlugin('content');
$dispatcher = JDispatcher::getInstance();
$article->text = $html;
$tmp_param = new JParameter();
$dispatcher->trigger('onContentPrepare', array ('com_content.article', &$article, &$tmp_param));
$html = $article->text;

数据查询

$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('contact.user_id, MAX(contact.id) AS id, contact.language');
$query->from('## __contact_details AS contact');
$query->where('contact.published = 1');
$query->group('contact.user_id, contact.language');
$query->order('contact.ordering');
$db->setQuery($query);
$rows = $db->loadObjectList();

数据插入

$query = $db->getQuery(true);
$query->insert('# __a')->set('id = 1');
$db->setQuery($query);
$db->query();

数据更新

$query = $db->getQuery(true);
$query->update($db->quoteName($this->_tbl));
$query->set('asset_id = ' . (int) $this->asset_id);
$query->where($db->quoteName($k) . ' = ' . (int) $this->$k);
$db->setQuery($query);
$db->query();

SQL数据查询

$db = JFactory::getDbo();
$sql = 'SELECT * FROM ## __users WHERE state=1';
$db->setQuery($sql);
$rows = $db->loadObjectList();
foreach($rows as $row) {
echo $row->name;
echo $row->email;
}

SQL插入数据并提取最后ID

$db = JFactory::getDbo();
$sql = 'INSERT INTO jos_xxx (name)VALUES('.$db->Quote('william').')';
$db->setQuery($sql);
$db->query();
$db->insertid();

所有UserID的数组

$db = JFactory::getDbo();
$sql = 'SELECT id FROM ## __users WHERE state=1';
$db->setQuery($sql);
$userIds = $db->loadColumn();
echo implode(', ', $userIds);

SQL更新记录

$db = JFactory::getDbo();
$title = '????';
$sql = 'UPDATE ## __content SET title='.$db->Quote($title).' WHERE id=1';
$db->setQuery($sql);
$db->query();

user存取数据

$user = JFactory::getUser($userId);
$user->name = 'newname';
$user->save();

menu存取数据

$app = JFactory::getApplication();
$menu = $app->getMenu();
$menuitem = $menu->getItem($Itemid);

parameter存取数据

JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.'/tables');
// class name = JTableMytable
$table = JTable::getInstance( 'mytable');
$table->load($id);
$params = new JParameter($table->params);
$params->set($key,$value);
$table->params = $params->toString();
$table->store();

基于JTable存取数据,必须有JTable实例

JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.'/tables');
// class name = XxxTableMytable
$table = JTable::getInstance( 'mytable', 'XxxTable');
$table->load($id);
$table->title = '???';
$table->store();

如果table与model类在同一个组件里,可以用JModel::getTable

JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.'/tables');
// class name = XxxTableMytable
$table = $this->getTable( 'mytable', 'XxxTable');
$table->load($id);
get item attribute
$articleParams = new JRegistry;
$articleParams->loadString($item->attribs);
$item->alternative_readmore = $articleParams->get('alternative_readmore');

set item attribute

JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.'/tables');
// class name = JTableMytable
$table = JTable::getInstance( 'mytable');
$table->load($id);
$articleParams = new JRegistry;
$table->attribs = $articleParams->toString();
$table->store();

基于JModel存取数据,必定存在JModel实例

$model = JModel::getInstance('Articles', 'ContentModel');
$model->setState('filter.state', 1);
$model->setState('list.ordering', 'publish_up');
$items = $model->getItems();

得到category对象

jimport( 'joomla.application.categories' );
$category = JCategories::getInstance('Content')->get($this->item->catid);

得到文章列表

$model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
$model->setState('params', new JRegistry(array()));
$model->setState('filter.state', 1);
$model->setState('list.ordering', 'publish_up');
$items = $model->getItems();

获取当前用户的可见等级,可见等级可以在后台设置

$view_levels = JFactory::getUser()->getAuthorisedViewLevels();

判断是否管理员

JFactory::getUser()->authorise('core.admin');
JFactory::getUser()->authorise('core.create', 'com_users');

Language, 判断当前语言

JFactory::getLanguage()->getTag() == 'en-GB';

redirect

$app = JFactory::getApplication();
$app->redirect(JRoute::_('index.php'), false);

得到文章地址

JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catid, $item->language));

调用CMS内容处理插件

$dispatcher = JDispatcher::getInstance();
JPluginHelper::importPlugin('content');
$this->item->text = '{flv}/'.$images->video.'{/flv}';
$dispatcher->trigger('onContentPrepare', array ('com_content.article', &$this->item, &$this->params, 0));
echo $this->item->text;

关键字:joomla, #db-# jfactory, array

版权声明

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处。如若内容有涉嫌抄袭侵权/违法违规/事实不符,请点击 举报 进行投诉反馈!

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部