当前位置: 首页 > news >正文

Joomla 2.x, 3.x 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(<post name>,  <data>, '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);

registry

就像全局变量,设置的值只在当前进程有效。常用于配置,或者component向module传递数据。

jimport('joomla.registry.registry');
$registry = JRegistry::getInstance($id);
$registry->get('vendor.param1', $default);
$registry->set('vendor.param1', $value);

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;

相关文章:

  • NavigationDuplicated: Avoided redundant navigation to current location: “/“
  • mysql 存储过程
  • Python tab补全
  • vue项目使用cookie、localStorage和sessionStorage进行储存数据
  • win7更改桌面路径
  • forEach循环遍历取id进行删除
  • CocoaPods升级安装三方库报错
  • router和route 传参接收参数的应用
  • 阿里巴巴SUI Mobile的使用
  • 关于时间向前推算到天,并且算闰年的计算
  • Android传递Bitmap的两种简单方式及其缺陷
  • Android中的mvp
  • 前端初始化项目对axios的封装和token的存储应用以及config.js代理的配置 比较全的了。
  • 开机自启动redis
  • 在一个div标签中平行放置两个echarts 环形图
  • $translatePartialLoader加载失败及解决方式
  • Android Studio:GIT提交项目到远程仓库
  • javascript 总结(常用工具类的封装)
  • JS数组方法汇总
  • Work@Alibaba 阿里巴巴的企业应用构建之路
  • 解决iview多表头动态更改列元素发生的错误
  • 力扣(LeetCode)965
  • 山寨一个 Promise
  • 详解NodeJs流之一
  • 学习笔记:对象,原型和继承(1)
  • 在Docker Swarm上部署Apache Storm:第1部分
  • 仓管云——企业云erp功能有哪些?
  • 好程序员大数据教程Hadoop全分布安装(非HA)
  • ​如何在iOS手机上查看应用日志
  • # Panda3d 碰撞检测系统介绍
  • #【QT 5 调试软件后,发布相关:软件生成exe文件 + 文件打包】
  • (附源码)springboot建达集团公司平台 毕业设计 141538
  • (附源码)ssm高校实验室 毕业设计 800008
  • (附源码)计算机毕业设计SSM在线影视购票系统
  • (论文阅读26/100)Weakly-supervised learning with convolutional neural networks
  • (学习日记)2024.04.10:UCOSIII第三十八节:事件实验
  • (一)80c52学习之旅-起始篇
  • * CIL library *(* CIL module *) : error LNK2005: _DllMain@12 already defined in mfcs120u.lib(dllmodu
  • .Net Core webapi RestFul 统一接口数据返回格式
  • .NET Core 项目指定SDK版本
  • .NET Remoting学习笔记(三)信道
  • .NET连接MongoDB数据库实例教程
  • .net流程开发平台的一些难点(1)
  • @RequestParam @RequestBody @PathVariable 等参数绑定注解详解
  • [C++]类和对象【下】
  • [CTF]php is_numeric绕过
  • [Fri 26 Jun 2015 ~ Thu 2 Jul 2015] Deep Learning in arxiv
  • [Grafana]ES数据源Alert告警发送
  • [java/jdbc]插入数据时获取自增长主键的值
  • [leetcode]Clone Graph
  • [Linux] 用LNMP网站框架搭建论坛
  • [luogu4162 SCOI2009] 最长距离(最短路)
  • [node]Node.js 模块系统
  • [NYOJ 536] 开心的mdd
  • [Qt]QMainWindow