在开发joomla扩展的时候,我们经常需要调试问题。最近我就遇到了一个奇怪的路径问题,发现joomla在后台调用的模型居然是前台的模型,隐约感觉到这个和路径有关。由于joomla是模块化设计,并不能知道到底是哪一个组件或者插件调用了代码。调试比较困难。这个时候可以使用debug_print_backtrace()来帮助我们调试php代码。

debug_print_backtrace()打印某个方法的调用堆栈

我遇到的问题就是可以确认一定有某个地方调用了addIncludePath方法,但不确定是哪一个文件。这个时候我做了一些改进,在addIncludePath方法中加入了debug_print_backtrace()。如下:

	/**
	 * Add a directory where \JModelLegacy should search for models. You may
	 * either pass a string or an array of directories.
	 *
	 * @param   mixed   $path    A path or array[sting] of paths to search.
	 * @param   string  $prefix  A prefix for models.
	 *
	 * @return  array  An array with directory elements. If prefix is equal to '', all directories are returned.
	 *
	 * @since   3.0
	 */
	public static function addIncludePath($path = '', $prefix = '')
	{
		static $paths;

		if (!isset($paths))
		{
			$paths = array();
		}

		if (!isset($paths[$prefix]))
		{
			$paths[$prefix] = array();
		}

		if (!isset($paths['']))
		{
			$paths[''] = array();
		}

		if (!empty($path))
		{
			jimport('joomla.filesystem.path');

			foreach ((array) $path as $includePath)
			{
				if (!in_array($includePath, $paths[$prefix]))
				{
					array_unshift($paths[$prefix], \JPath::clean($includePath));
				}

				if (!in_array($includePath, $paths['']))
				{
					array_unshift($paths[''], \JPath::clean($includePath));
				}
			}
		}

		echo "<pre>";
			print_r($paths);
			debug_print_backtrace();
		echo "</pre>";
		return $paths[$prefix];
	}

输出的结果

此时就可以看到每一次调用这个方法后path的变化,且能够追踪到具体的调用文件,结果一目了然。

感悟

在php中,使用的debug_print_backtrace()方法可以帮助我们解决负责的调试,特别是在CMS这些框架程序中。

作者: 樱木花道

Joomla程序员,从J1.5到J4.x始终都在做Joomla相关开发定制工作,有超过10年行业经验,国内Joomla扩展开发商ZMAX团队的核心成员

作者网站:ZMAX程序人

评论 (0)

  • 最新在前
  • 最佳在前