CI框架loader类分析

_ci_autoloader 私有方法分析

if (file_exists(APPPATH.'config/autoload.php'))
{
	include(APPPATH.'config/autoload.php');
}

if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/autoload.php'))
{
	include(APPPATH.'config/'.ENVIRONMENT.'/autoload.php');
}

if ( ! isset($autoload))
{
	return;
}

加载自动加载类配置文件

// Autoload packages
if (isset($autoload['packages']))
{
	foreach ($autoload['packages'] as $package_path)
	{
		$this->add_package_path($package_path);
	}
}

加载自动加载自动加载文件中packages地址

// Load any custom config file
if (count($autoload['config']) > 0)
{
	foreach ($autoload['config'] as $val)
	{
		$this->config($val);
	}
}

自动加载config文件

// Autoload helpers and languages
foreach (array('helper', 'language') as $type)
{
	if (isset($autoload[$type]) && count($autoload[$type]) > 0)
	{
		$this->$type($autoload[$type]);
	}
}

自动加载helper和language类配置文件

// Autoload drivers
if (isset($autoload['drivers']))
{
	$this->driver($autoload['drivers']);
}

自动加载library扩展类

// Load libraries
if (isset($autoload['libraries']) && count($autoload['libraries']) > 0)
{
	// Load the database driver.
	if (in_array('database', $autoload['libraries']))
	{
		$this->database();
		$autoload['libraries'] = array_diff($autoload['libraries'], array('database'));
	}

	// Load all other libraries
	$this->library($autoload['libraries']);
}

自动加载模型类

// Autoload models
if (isset($autoload['model']))
{
	$this->model($autoload['model']);
}

add_package_path

$path = rtrim($path, '/').'/';

array_unshift($this->_ci_library_paths, $path);
array_unshift($this->_ci_model_paths, $path);
array_unshift($this->_ci_helper_paths, $path);

$this->_ci_view_paths = array($path.'views/' => $view_cascade) + $this->_ci_view_paths;

// Add config file path
$config =& $this->_ci_get_component('config');
$config->_config_paths[] = $path;

return $this;

此方法为将扩展类库的地址新增到系统的配置文件中,以便后期的加载

helper

/**
 * Helper Loader
 *
 * @param	string|string[]	$helpers	Helper name(s)
 * @return	object
 */
public function helper($helpers = array())
{
	foreach ($this->_ci_prep_filename($helpers, '_helper') as $helper)
	{
		if (isset($this->_ci_helpers[$helper]))
		{
			continue;
		}

		// Is this a helper extension request?
		$ext_helper = config_item('subclass_prefix').$helper;
		$ext_loaded = FALSE;


		foreach ($this->_ci_helper_paths as $path)
		{
			if (file_exists($path.'helpers/'.$ext_helper.'.php'))
			{
				include_once($path.'helpers/'.$ext_helper.'.php');
				$ext_loaded = TRUE;
			}
		}

		// If we have loaded extensions - check if the base one is here
		if ($ext_loaded === TRUE)
		{
			$base_helper = BASEPATH.'helpers/'.$helper.'.php';
			if ( ! file_exists($base_helper))
			{
				show_error('Unable to load the requested file: helpers/'.$helper.'.php');
			}

			include_once($base_helper);
			$this->_ci_helpers[$helper] = TRUE;
			log_message('info', 'Helper loaded: '.$helper);
			continue;
		}

		// No extensions found ... try loading regular helpers and/or overrides
		foreach ($this->_ci_helper_paths as $path)
		{
			if (file_exists($path.'helpers/'.$helper.'.php'))
			{
				include_once($path.'helpers/'.$helper.'.php');

				$this->_ci_helpers[$helper] = TRUE;
				log_message('info', 'Helper loaded: '.$helper);
				break;
			}
		}

		// unable to load the helper
		if ( ! isset($this->_ci_helpers[$helper]))
		{
			show_error('Unable to load the requested file: helpers/'.$helper.'.php');
		}
	}

	return $this;
}

优先加载系统扩展类
如果需要加载系统扩展类,则需要加载系统的函数
加载自定义扩展函数库

_ci_load_library

此方法用于加载扩展类库,加载一共分两种方式

1._ci_load_stock_library

如果该类是CI系统核心的类库,则需要_ci_load_stock_library方法进行加载

2._ci_init_library

如果是开发者自定义的,则直接初始化该类即可

注:为何加载需要分开?

由于开发者可能扩展了系统类库,所以当加载核心类库的时候需要优先查看是否存在扩展类,存在则还需要加载开发者扩展的类库

_ci_init_library

此方法用于初始化类库
先是找到需要在家类库的文件,然后判断是否已加载,如果未加载则进行加载,已加载则直接直接返回

_ci_load

此方法用于获取模板内容

// This allows anything loaded using $this->load (views, files, etc.)
// to become accessible from within the Controller and Model functions.
$_ci_CI =& get_instance();
foreach (get_object_vars($_ci_CI) as $_ci_key => $_ci_var)
{
	if ( ! isset($this->$_ci_key))
	{
		$this->$_ci_key =& $_ci_CI->$_ci_key;
	}
}

此方法里面的这段代码用于在模板中也可使用当前controller里已加载的类库以及各种资源

先获取到需要展现模板的文件,然后通过ob_start的特性把模板以后的信息放入一个变量中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
你好,我是C知道。关于你的问题,我可以回答。以下是使用PyTorch框架编写LeNet分网络的代码: ```python import torch import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms import torchvision.datasets as datasets # 定义LeNet网络结构 class LeNet(nn.Module): def __init__(self): super(LeNet, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool1 = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.pool2 = nn.MaxPool2d(2, 2) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.pool1(torch.relu(self.conv1(x))) x = self.pool2(torch.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = torch.relu(self.fc1(x)) x = torch.relu(self.fc2(x)) x = self.fc3(x) return x # 加载数据集 train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transforms.ToTensor()) test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transforms.ToTensor()) # 定义训练参数 batch_size = 64 learning_rate = .001 num_epochs = 10 # 定义数据加载器 train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False) # 定义模型、损失函数和优化器 model = LeNet() criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=learning_rate) # 训练模型 for epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader): optimizer.zero_grad() outputs = model(images) loss = criterion(outputs, labels) loss.backward() optimizer.step() if (i+1) % 100 == : print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, i+1, len(train_loader), loss.item())) # 测试模型 model.eval() with torch.no_grad(): correct = total = for images, labels in test_loader: outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size() correct += (predicted == labels).sum().item() print('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total)) ``` 希望这个回答能够帮助到你。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值