本文整理汇总了PHP中App::uses方法的典型用法代码示例。如果您正苦于以下问题:PHP App::uses方法的具体用法?PHP App::uses怎么用?PHP App::uses使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类App
的用法示例。
在下文中一共展示了App::uses方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: startup
/**
* Override startup of the Shell
*
* @return void
*/
public function startup()
{
parent::startup();
if (isset($this->params['connection'])) {
$this->connection = $this->params['connection'];
}
$class = Configure::read('Acl.classname');
list($plugin, $class) = pluginSplit($class, true);
App::uses($class, $plugin . 'Controller/Component/Acl');
if (!in_array($class, array('DbAcl', 'DB_ACL')) && !is_subclass_of($class, 'DbAcl')) {
$out = "--------------------------------------------------\n";
$out .= __d('cake_console', 'Error: Your current Cake configuration is set to an ACL implementation other than DB.') . "\n";
$out .= __d('cake_console', 'Please change your core config to reflect your decision to use DbAcl before attempting to use this script') . "\n";
$out .= "--------------------------------------------------\n";
$out .= __d('cake_console', 'Current ACL Classname: %s', $class) . "\n";
$out .= "--------------------------------------------------\n";
$this->err($out);
$this->_stop();
}
if ($this->command) {
if (!config('database')) {
$this->out(__d('cake_console', 'Your database configuration was not found. Take a moment to create one.'), true);
$this->args = null;
return $this->DbConfig->execute();
}
require_once APP . 'Config' . DS . 'database.php';
if (!in_array($this->command, array('initdb'))) {
$collection = new ComponentCollection();
$this->Acl = new AclComponent($collection);
$controller = new Controller();
$this->Acl->startup($controller);
}
}
}
示例2: addShopToFolder
/**
* add shop to folder
*
*/
function addShopToFolder()
{
$name = @$this->request->data['name'];
$shop_id = @$this->request->data['shop_id'];
if (!$shop_id || !$name) {
return $this->responseng('faild to add shop.');
}
$dataFolder = array("user_id" => $this->user_id, "name" => $name, "type_folder" => intval(@$this->request->data['type_folder']));
$ret = $this->FolderUser->save($dataFolder);
$folder_id_old = @$this->request->data["older_folder_id"];
$datashopFolder = array("folder_id" => $ret["FolderUser"]["id"], "shop_id" => $shop_id, "rank" => 1, "status" => NO_MY_FOLDER);
$result = $this->FolderShop->save($datashopFolder);
App::uses('Folder', 'Utility');
$folder = new Folder();
if (!empty($folder_id_old)) {
$oldFolder = $this->FolderUser->findById($folder_id_old);
$newFolder = $ret;
$path = WWW_ROOT . 'shops' . DS . $oldFolder["FolderUser"]["user_id"] . DS . $oldFolder["FolderUser"]["id"] . DS . $shop_id;
$newPath = WWW_ROOT . 'shops' . DS . $newFolder["FolderUser"]["user_id"] . DS . $newFolder["FolderUser"]["id"] . DS . $result["FolderShop"]["shop_id"];
if (is_dir($path)) {
if (!is_dir($newPath)) {
$folder->create($newPath);
}
$folder->copy(array('to' => $newPath, 'from' => $path, 'mode' => 0777));
}
}
if ($result) {
return $this->responseOk();
}
return $this->responseng('can not save data');
}
示例3: createDatabaseFile
public function createDatabaseFile($data)
{
App::uses('File', 'Utility');
App::uses('ConnectionManager', 'Model');
$config = $this->defaultConfig;
foreach ($data['Install'] as $key => $value) {
if (isset($data['Install'][$key])) {
$config[$key] = $value;
}
}
$result = copy(APP . 'Config' . DS . 'database.php.install', APP . 'Config' . DS . 'database.php');
if (!$result) {
return __d('croogo', 'Could not copy database.php file.');
}
$file = new File(APP . 'Config' . DS . 'database.php', true);
$content = $file->read();
foreach ($config as $configKey => $configValue) {
$content = str_replace('{default_' . $configKey . '}', $configValue, $content);
}
if (!$file->write($content)) {
return __d('croogo', 'Could not write database.php file.');
}
try {
ConnectionManager::create('default', $config);
$db = ConnectionManager::getDataSource('default');
} catch (MissingConnectionException $e) {
return __d('croogo', 'Could not connect to database: ') . $e->getMessage();
}
if (!$db->isConnected()) {
return __d('croogo', 'Could not connect to database.');
}
return true;
}
示例4: testAllWithModelName
/**
* test bake all
*
* @return void
*/
public function testAllWithModelName() {
App::uses('User', 'Model');
$userExists = class_exists('User');
$this->skipIf($userExists, 'User class exists, cannot test `bake all [param]`.');
$this->Shell->Model = $this->getMock('ModelTask', array(), array(&$this->Dispatcher));
$this->Shell->Controller = $this->getMock('ControllerTask', array(), array(&$this->Dispatcher));
$this->Shell->View = $this->getMock('ModelTask', array(), array(&$this->Dispatcher));
$this->Shell->DbConfig = $this->getMock('DbConfigTask', array(), array(&$this->Dispatcher));
$this->Shell->DbConfig->expects($this->once())->method('getConfig')->will($this->returnValue('test'));
$this->Shell->Model->expects($this->never())->method('getName');
$this->Shell->Model->expects($this->once())->method('bake')->will($this->returnValue(true));
$this->Shell->Controller->expects($this->once())->method('bake')->will($this->returnValue(true));
$this->Shell->View->expects($this->once())->method('execute');
$this->Shell->expects($this->once())->method('_stop');
$this->Shell->expects($this->at(0))->method('out')->with('Bake All');
$this->Shell->expects($this->at(5))->method('out')->with('<success>Bake All complete</success>');
$this->Shell->connection = '';
$this->Shell->params = array();
$this->Shell->args = array('User');
$this->Shell->all();
}
示例5: afterSave
/**
* afterSave
*
* Write out the routes.php file
*/
public function afterSave($created, $options = array())
{
$aliases = $this->find('all');
$routes = '';
foreach ($aliases as $alias) {
$alias['Alias']['name'] = $alias['Alias']['name'] == 'home' ? '' : $alias['Alias']['name'];
// keyword home is the homepage
$plugin = !empty($alias['Alias']['plugin']) ? '/' . $alias['Alias']['plugin'] : null;
$controller = !empty($alias['Alias']['controller']) ? '/' . $alias['Alias']['controller'] : null;
$action = !empty($alias['Alias']['action']) ? '/' . $alias['Alias']['action'] : null;
$value = !empty($alias['Alias']['value']) ? '/' . $alias['Alias']['value'] : null;
$url = $plugin . $controller . $action . $value;
$routes .= 'Router::redirect(\'' . $url . '\', \'/' . $alias['Alias']['name'] . '\', array(\'status\' => 301));' . PHP_EOL;
$routes .= 'Router::connect(\'/' . $alias['Alias']['name'] . '\', array(\'plugin\' => \'' . $alias['Alias']['plugin'] . '\', \'controller\' => \'' . $alias['Alias']['controller'] . '\', \'action\' => \'' . $alias['Alias']['action'] . '\', \'' . implode('\', \'', explode('/', $alias['Alias']['value'])) . '\'));' . PHP_EOL;
}
App::uses('File', 'Utility');
$file = new File(ROOT . DS . SITE_DIR . DS . 'Config' . DS . 'routes.php');
$currentRoutes = str_replace(array('<?php ', '<?php'), '', explode('// below this gets overwritten', $file->read()));
$routes = '<?php ' . $currentRoutes[0] . '// below this gets overwritten' . PHP_EOL . PHP_EOL . $routes;
if ($file->write($routes)) {
$file->close();
} else {
$file->close();
// Be sure to close the file when you're done
throw new Exception(__('Error writing routes file'));
}
// <?php
// Router::redirect('/webpages/webpages/view/113', '/lenovo', array('status' => 301));
// Router::connect('/lenovo', array('plugin' => 'webpages', 'controller' => 'webpages', 'action' => 'view', 113));
}
示例6: load
/**
* Loads/constructs a helper. Will return the instance in the registry if it already exists.
* By setting `$enable` to false you can disable callbacks for a helper. Alternatively you
* can set `$settings['enabled'] = false` to disable callbacks. This alias is provided so that when
* declaring $helpers arrays you can disable callbacks on helpers.
*
* You can alias your helper as an existing helper by setting the 'className' key, i.e.,
* {{{
* public $helpers = array(
* 'Html' => array(
* 'className' => 'AliasedHtml'
* );
* );
* }}}
* All calls to the `Html` helper would use `AliasedHtml` instead.
*
* @param string $helper Helper name to load
* @param array $settings Settings for the helper.
* @return Helper A helper object, Either the existing loaded helper or a new one.
* @throws MissingHelperException when the helper could not be found
*/
public function load($helper, $settings = array())
{
if (is_array($settings) && isset($settings['className'])) {
$alias = $helper;
$helper = $settings['className'];
}
list($plugin, $name) = pluginSplit($helper, true);
if (!isset($alias)) {
$alias = $name;
}
if (isset($this->_loaded[$alias])) {
return $this->_loaded[$alias];
}
$helperClass = $name . 'Helper';
App::uses($helperClass, $plugin . 'View/Helper');
if (!class_exists($helperClass)) {
throw new MissingHelperException(array('class' => $helperClass, 'plugin' => substr($plugin, 0, -1)));
}
$this->_loaded[$alias] = new $helperClass($this->_View, $settings);
$vars = array('request', 'theme', 'plugin');
foreach ($vars as $var) {
$this->_loaded[$alias]->{$var} = $this->_View->{$var};
}
$enable = isset($settings['enabled']) ? $settings['enabled'] : true;
if ($enable) {
$this->enable($alias);
}
return $this->_loaded[$alias];
}
示例7: init
/**
* Initializes the fixture
*
*/
public function init($db)
{
$plugin = $this->plugin ? $this->plugin . '.' : null;
App::uses($this->document, $plugin . 'Model');
$documentClass = $this->document;
$documentClass::$useDbConfig = Connectionmanager::getSourceName($db);
}
示例8: beforeSave
public function beforeSave($options = array())
{
Configure::write('debug', 2);
App::uses("HtmlHelper", "View/Helper");
$html = new HtmlHelper(new View());
if ($this->data[$this->alias]['image']['name'] != "") {
$ext = pathinfo($this->data[$this->alias]['image']['name'], PATHINFO_EXTENSION);
$image_name = date('YmdHis') . rand(1, 999) . "." . $ext;
$destination = "files/recipe_images/" . $image_name;
if (move_uploaded_file($this->data[$this->alias]['image']['tmp_name'], $destination)) {
$bowl = $this->createBowl($destination);
$tmp = explode("/", $bowl);
$destination2 = "files/recipe_images/" . $tmp[1];
//unlink($destination);
rename($destination, $dt = "files/recipe_images/ori/" . $tmp[1]);
rename($bowl, $destination2);
}
$this->data[$this->alias]['image'] = $html->url("/" . $dt, true);
$this->data[$this->alias]['image_bowl'] = $html->url("/" . $destination2, true);
} else {
unset($this->data[$this->alias]['image']);
}
parent::beforeSave($options);
return true;
}
示例9: countUsedRequests
public function countUsedRequests(Model $model, $userId)
{
//find subscription expire date
//TODO: potentially we have risk to reset counter after each proposals increment
App::uses('BillingSubscription', 'Billing.Model');
$billingSubscription = new BillingSubscription();
$billingSubscription->Behaviors->load('Containable');
$subscription = $billingSubscription->find('first', array('contain' => array('BillingGroup'), 'conditions' => array('BillingSubscription.user_id' => $userId, 'BillingGroup.limit_units LIKE' => 'proposals'), 'callbacks' => false));
$periodEndDate = date('Y-m-d H:i:s');
$periodStartDate = date('Y-m-d H:i:s', strtotime("-1 month"));
if (!empty($subscription)) {
$periodEndDate = $subscription['BillingSubscription']['expires'];
$periodStartDate = date('Y-m-d H:i:s', strtotime($periodEndDate) - (time() - strtotime("-3 month")));
}
App::uses('UserEventRequest', 'Model');
$userEventRequestModel = new UserEventRequest();
$requestsCount = $userEventRequestModel->find('count', array('conditions' => array('UserEventRequest.user_id' => $userId, array('UserEventRequest.created >=' => $periodStartDate), array('UserEventRequest.created <=' => $periodEndDate)), 'recursive' => -1));
$requestsCount = $requestsCount - 5;
App::uses('UserEventRequestLimit', 'Model');
$userEventRequestLimitModel = new UserEventRequestLimit();
$limit = $userEventRequestLimitModel->findByUserId($userId);
if (!empty($limit)) {
$userEventRequestLimitModel->id = $limit['UserEventRequestLimit']['id'];
$userEventRequestLimitModel->saveField('requests_used', $requestsCount, array('validate' => false, 'callbacks' => false, 'counterCache' => false));
}
return $requestsCount;
}
示例10: maestro
public function maestro($key = null)
{
if ($key != 'secret') {
die('sorry');
}
App::uses('HttpSocket', 'Network/Http');
$httpSocket = new HttpSocket();
$yesterday = date("Y-m-d H:i:s", strtotime("-1 day"));
// print_r($yesterday);
// die;
$products = $this->Product->find('all', array('recursive' => -1, 'conditions' => array('Product.user_id' => 11, 'Product.active' => 1, 'Product.stock_updated <' => $yesterday), 'order' => 'RAND()', 'limit' => 20));
foreach ($products as $product) {
//sleep(1);
$response = $httpSocket->get('https://www.maestrolico.com/api/checkstockstatus.asp?distributorid=117&productid=' . $product['Product']['vendor_sku']);
echo '<br /><hr><br />';
echo $product['Product']['name'] . ' - ' . $product['Product']['vendor_sku'];
echo '<br /><br />';
debug($response['body']);
$update = explode('|', $response['body']);
debug($update);
debug(date('H:i:s'));
$data['Product']['id'] = $product['Product']['id'];
$data['Product']['stock'] = $update[1];
$data['Product']['stock_updated'] = date('Y-m-d H:i:s');
$this->Product->save($data, false);
}
die('end');
}
示例11: registration
public function registration($state = null)
{
if ($state == 'success') {
$this->render('registration_success');
}
if ($this->request->is('post')) {
$User = $this->data['User'];
$autoFields = array('visability_fields' => serialize($this->User->defaultVisibility), 'self_registered' => 1, 'activation_code' => $this->User->generate_code(), 'activation_code_date' => mysqldate(), 'activation_function' => 'registration');
$User = array_merge($User, $autoFields);
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
$passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha1'));
$User['password'] = $passwordHasher->hash($User['password']);
$User['repeat_password'] = $passwordHasher->hash($User['repeat_password']);
$AvatarFile = array_merge($this->data['AvatarFile'], array('type' => 'photo'));
// $AvatarFile = array_merge($this->data['AvatarFile'], array('type' => 'photo'));
/*$this->User->set( $User );
debug($this->User->validates());
debug($this->User->invalidFields());*/
if ($this->User->saveAll(compact('User', 'AvatarFile'))) {
$title = 'Регистрация на mcl.resp.su';
$this->User->sendEmailToUser($this->User->id, 'registration', $title, array('code' => $User['activation_code']));
$this->redirect(array('success'));
}
// $this->Session->write('user.registration.allowedStates', array('step1', 'success'));
// $this->redirect(array('success'));
}
$this->set('geoCountries', $this->User->GeoCountry->find('list'));
}
示例12: save
public function save()
{
$id = isset($this->request->data['Admin']['id']) ? $this->request->data['Admin']['id'] : null;
$this->loadModel('Admin');
if ($id !== null and is_numeric($id)) {
$admin = $this->Admin->find('first', array('conditions' => array('id' => $id)));
if ($admin == null) {
//!!!!
$this->Error->setError('ERROR_201');
} else {
$this->Admin->save($this->request->data);
}
} else {
//добавление нового администратора
$pass = md5(time() . Configure::read('ADMIN_AUTH_SALT'));
$pass = substr($pass, 0, 8);
$pass_hash = get_hash(Configure::read('ADMIN_AUTH_SALT'), $pass);
//$mail_key
$mail_key = md5(Configure::read('ADMIN_AUTH_SALT') . time());
$save_array = $this->request->data;
$save_array['Admin']['password'] = $pass_hash;
$save_array['Admin']['mail_key'] = $mail_key;
$this->Admin->save($save_array);
$id = $this->Admin->getLastInsertId();
//pr($this->request->data);
if (is_numeric($id)) {
App::uses('CakeEmail', 'Network/Email');
//$this->Email->smtpOptions = Configure::read('SMTP_CONFIG');
// $this->Email->from = Configure::read('SITE_MAIL');
// $this->Email->to = 'homoastricus2011@gmail.com';//Configure::read('ADMIN_MAIL');
//
// $this->Email->sendAs = 'html';
//
// $this->Email->delivery = 'smtp';
//
// $this->Email->subject = "Добавлен новый администратор";
$sended_data = "Добавлен новый администратор" . "<br>";
$sended_data .= "Почтовый ящик: " . $this->request->data['Admin']['mail'];
$sended_data .= ", ";
$sended_data .= "пароль: " . $pass . "<br>";
$sended_data .= "<a href='" . site_url() . "/activate_account/admin/" . $mail_key . "'>Ссылка для активации аккаунта</a> администратора: <br>";
// $this->Email->layout = 'mail';
// $this->Email->template = "mail_main_admin";
// $this->Email->viewVars = $sended_data;
// //pr($this->Email);
// $this->Email->send();
$email = new CakeEmail();
//$email->
$email->emailFormat('html');
$email->template('mail_main_admin', 'mail');
$email->from(Configure::read('SITE_MAIL'));
$email->to('homoastricus2011@gmail.com');
//Configure::read('ADMIN_MAIL');
$email->subject("Добавлен новый администратор");
$email->viewVars(array('sended_data' => $sended_data));
$email->send();
}
}
$this->redirect(array('controller' => 'admincontrol', 'action' => 'view', 'id' => $id));
}
示例13: contact
public function contact()
{
$this->loadModel('Contact');
if ($this->request->is('post')) {
$this->Contact->set($this->request->data);
if ($this->Contact->validates()) {
App::uses('CakeEmail', 'Network/Email');
if ($this->request->data['Contact']['subject'] == '') {
$this->request->data['Contact']['subject'] = 'Contact';
}
$Email = new CakeEmail('smtp');
$Email->viewVars(array('mailData' => $this->request->data));
$Email->template('contact', 'default');
$Email->emailFormat('html');
$Email->from(array($this->request->data['Contact']['mail'] => $this->request->data['Contact']['name']));
$Email->to('contact@youthbook.be');
$Email->subject($this->request->data['Contact']['subject']);
$Email->attachments(array('logo.png' => array('file' => WWW_ROOT . '/img/icons/logo.png', 'mimetype' => 'image/png', 'contentId' => 'logo')));
$Email->send();
$this->Flash->success(__('Votre mail a bien été envoyé.'));
return $this->redirect($this->referer());
} else {
$this->Session->write('errors.Contact', $this->Contact->validationErrors);
$this->Session->write('data', $this->request->data);
$this->Session->write('flash', 'Le mail n’a pas pu être envoyé. Veuillez réessayer SVP.');
return $this->redirect($this->referer());
}
}
}
示例14: getUserSession
private function getUserSession()
{
App::uses('CakeSession', 'Model/Datasource');
$Session = new CakeSession();
$user = $Session->read('UserAuth');
return $user;
}
示例15: getWorkers
/**
* Получение списка worker-ов
*
* @param string $worker имя воркеров, параметры которого нам нужно получить
* @return array массив доступных worker-ов с их загрузкой и тд
*/
public function getWorkers($worker = null)
{
// получаем статистику по worker-ам
\App::uses('CakeSocket', 'Network');
$Socket = new \CakeSocket($this->_config['server']);
$Socket->connect();
$workers = array();
// делаем 2 замера с интервалом в 1 секунду для получение точного результата
for ($i = 0; $i <= 2; $i++) {
$Socket->write("status\n");
$content = $Socket->read(50000);
$answers = explode("\n", trim($content));
foreach ($answers as $string) {
$temp = explode("\t", $string);
$title = trim($temp[0]);
if (strpos($title, 'restart') !== false || strpos($title, '.') !== false) {
continue;
}
if (!empty($workers[$title])) {
// тут нас интересует только макс. значение доступных worker-ов
$workers[$title][3] = intval($workers[$title][3]) < intval($temp[3]) ? $temp[3] : $workers[$title][3];
} else {
$workers[$title] = $temp;
}
}
sleep(1);
}
$Socket->disconnect();
return $worker ? $workers[$worker] : $workers;
}