I could reproduce similar behavior using below script:
<?php require __DIR__ . '/vendor/autoload.php'; use yiibaseErrorException; function handleError($code, $message, $file, $line) { throw new ErrorException($message, $code, $code, $file, $line); } set_error_handler('handleError'); class Klazz { public static function foo() { static::bar(); } private static function bar() { eval("echo $foo['bar'];"); } } Klazz::foo();
$ php -v
PHP 7.0.7 (cli) (built: May 25 2016 17:35:28) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies
with Xdebug v2.4.0, Copyright (c) 2002-2016, by Derick Rethans
$ php xdebugtest.php
PHP Fatal error: Uncaught yiibaseErrorException: Expected array for frame 0 in Unknown:0
Stack trace:
#0 {main}
thrown in Unknown on line 0
Just when use yiibaseErrorException;
line removed, I could get expected result:
$ php xdebugtest.php
PHP Fatal error: Uncaught ErrorException: Undefined variable: foo in /.../xdebugtest.php(22) : eval()'d code:1
Stack trace:
#0 /.../xdebugtest.php(22) : eval()'d code(1): handleError(8, 'Undefined varia...', '/...', 1, Array)
#1 /.../xdebugtest.php(22): eval()
#2 /.../xdebugtest.php(17): Klazz::bar()
#3 /.../xdebugtest.php(26): Klazz::foo()
#4 {main}
thrown in /.../xdebugtest.php(22) : eval()'d code on line 1
I have just created on basic example for fetching of data from table using this and it worked well, but now I want to write query using yii query builder
($list= Yii::$app()->db->createCommand('select * from country')->queryAll();)
but in this case I am getting error for
«PHP Fatal Error – yiibaseErrorException», «Class ‘appmodelsYii’ not found».
Matt
14.5k26 gold badges95 silver badges148 bronze badges
asked Jan 6, 2016 at 7:37
0
Your Model is not properly namespace
Read PHP Namespace
Change Your Query Code as
$list= Yii::$app()->db->createCommand('select * from country')->queryAll();
Change Your Country Model as
class Country extends yiidbActiveRecord
{
public static function getAllCountry()
{
$list = Yii::$app->db->createCommand('select * from country')->queryAll();
echo "<pre>" . print_r($list);
die;
}
}
and to get list from Your Controller:
appmodelsCountry::getAllCountry();
answered Jan 6, 2016 at 7:44
Double HDouble H
4,1001 gold badge15 silver badges26 bronze badges
1
public function actionIndex()
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
if (Yii::app ()->user->isGuest) {
$this->redirect ( Yii::app ()->createUrl ( 'site/login' ) );
} else {
// Export Scenario
$exportScenario = 'incoming';
$exportScenario2 = 'outgoing';
$exportScenario3 = 'missed';
// Default date
$date = null;
$fromDate = null;
$toDate = null;
//Model definitions
$model = new Logs ();
//get incoming calls
$incalls = $model->getInCalls();
// For filtering grid
$filtersForm = new GridForm ();
// Get filtered data
$filteredData = $filtersForm->filter ( $incalls );
$inDataProvider = new yiidataArrayDataProvider ( $filteredData, [ // Define pagination
'pagination' => [
'pageSize' => 10000
]
] );
//get outgoing calls
$outcalls = $model->getOutCalls();
// For filtering grid
$filtersForm = new GridForm ();
// Get filtered data
$filteredData = $filtersForm->filter ( $outcalls );
$outDataProvider = new CArrayDataProvider ( $filteredData, [ // Define pagination
'pagination' => [
'pageSize' => 10000
]
] );
//get missed calls
$missedcalls = $model->getMissedCalls();
// For filtering grid
$filtersForm = new GridForm ();
// Get filtered data
$filteredData = $filtersForm->filter ( $missedcalls );
$missedDataProvider = new CArrayDataProvider ( $filteredData, [ // Define pagination
'pagination' => [
'pageSize' => 10000
]
] );
// For Excel exporting and getting printable versions
if (isset ( $_GET ['export'] )) {
$exportHash = $_GET ['id'];
if ($_GET ['export'] == 'excel') {
// Exporting excel
Common::export ( null, 'get', $exportHash );
} else {
// Getting printable html
Common::export ( null, 'get', $exportHash, 'html' );
}
}
$this->render('index', [
'exportScenario' => $exportScenario,
'exportScenario2' => $exportScenario2,
'exportScenario3' => $exportScenario3,
'inDataProvider'=>$inDataProvider,
'outDataProvider'=>$outDataProvider,
'missedDataProvider'=>$missedDataProvider,
'filtersForm' => $filtersForm,
'date'=>$date,
'model'=>$model,
'incalls'=>$incalls
]);
}
}
i am run this site http://localhost/master/web/index.php?r=site/index but an error Call to undefined method Yii::app() shows up. Am using yii2 basic app. Any help would be appreciated.
the above code is an extract from the sitecontroller.php and the error stems from this line
if (Yii::app ()->user->isGuest) {
$this->redirect ( Yii::app ()->createUrl ( ‘site/login’ ) );
}
-
Yii
В YII запускаю через php yii … скрипт, который должен выполняться минут 10, но через несколько минут выскакивает ошибка PHP Fatal Error ‘yiibaseErrorException’ with message ‘Out of memory (allocated 1552941056) (tried to allocate 67108864 bytes)’. Как с этим бороться? Или как лучше организовать работу парсера, чтобы не грузил так сервер? Спасибо.
-
Вопрос заданболее трёх лет назад
-
464 просмотра
9
комментариев
-
Вы расчитываете получить ответ на вопрос:
«Я написал скрипт, который кушает много памяти — как мне его улучшить»?
Или я чего-то не понял… -
Мда…. Парсер и столько памяти? Он что в бесконечный цикл попал…..
-
Артём
@DeOne Автор вопроса
Express777: да, цикл бесконечный, прерывается по условию.
-
Артём
@DeOne Автор вопроса
Алексей: скрипт самый обычный, делаем запрос, заносим в массив, все это а цикле и потом сохраняем в базу.
-
Артём: Ваш вопрос немного изменился.
Теперь он звучит — «Я написал самый обычный скрипт, который кушает много памяти — как мне его улучшить»?
Как мы можем вам помочь, кроме гадания на кофейной гуще?
У вас уже выделено 1.5Гб и очередной операцией вы выделяете 67Мб.
Либо у вас большие данные и надо как-то оптимизировать алгоритм, либо вы где-то забываете обнулить переменную и «напихиваете» в нее все больше и больше данных и куда-то ее еще в цикле добавляете. -
Артём
@DeOne Автор вопроса
Алексей: давай, переменная наполняется, в конце концов в ней может быть 5 миллионов индексов, но и это не предел. Хватает только на 4 миллиона. Это все в массиве, а в конце делаю implode и заношу в базу данных.
-
Артём
@DeOne Автор вопроса
-
Артём: Рано или поздно ваш подход приведет к переполнению любой памяти.
Если не имеете возможности тут подробно описать что вы храните и обрабатываете, то вряд ли получите внятный совет.
Вариантов может быть масса — может быть что-то можно оптимизировать в плане хранения в памяти (например строки с целыми запаковать в бинарные данные что сократит потребление памяти), или есть возможность разбить работу на блоки по 1000 записей, или что-то можно запаковать в gzip, или если на сервере очень много памяти — использовать /dev/shm/ как временный диск в памяти или еще какие-то есть варианты. -
Артём
@DeOne Автор вопроса
Пригласить эксперта
Ответы на вопрос 1
@R0dger
Laravel/Yii/2 AngularJs PHP RESTful API
Смотря что у Вас делает парсер, все индивидуально (может быть плохо написан сам скрипт, может использовать AR c 10000 записями без iterator и т.д.), плюс может можно побить работу на этапы или еще… про сферического коня в вакууме тяжело говорить.
-
Артём
@DeOne Автор вопроса
AR висит, но изменяется только в самом конце, а до этого не доходит.
Похожие вопросы
-
Показать ещё
Загружается…
04 июн. 2023, в 12:07
2000 руб./за проект
04 июн. 2023, в 12:06
1000 руб./за проект
04 июн. 2023, в 12:06
30000 руб./за проект
Минуточку внимания
Здравстуйте, столкнулась с такой проблемой, некий запрос «name» который ввёл пользователь не сохраняется в базе данных да ещё и вылетает эта глупая ошибка с которой вообще не могу управиться.. видимо я глупее неё..подскажите пожалуйста в чём загвоздка?
Вот данная ошибка в полном формате:
Код: Выделить всё
PHP Fatal Error – yiibaseErrorException
Class 'appmodels' not found
1. in /var/www/u0598324/public_html/webstels.com/models/ShopPromoItem.php at line 40
return [
'status' => 'Статус',
];
}
public static function get($id)
{
$item = ShopPromoItem::findOne($id);
$class = 'app\models\' . $item->class;
return $class::findOne($id);
}
public function getTitle()
{
return Html::encode($this->title);
}
public function getPriceArray()
{
2. yiibaseErrorHandler::handleFatalError()
$_GET = [
'username' => 'swallowsveta1997',
];
$_POST = [
'_csrf' => '2dWdOMdf_z2HrgmbtpnKKN1f-mQnpLEkeqpEkFg8zj6OoOR-sAa2DrOcQ-GG7otyuxSIXEzn6R0M5jX5Cw2cVw==',
'ShopPromoItemBuyForm' => [
'name' => 'name',
'item_id' => '1',
],
];
$_COOKIE = [
'_identity' => 'd669e918ca5f102ab0802a521e1d3fc241689f04dbb51253b7b8ab7b54713c5ca:2:{i:0;s:9:"_identity";i:1;s:50:"[22727,"gkEvlaqhpnAtz8mz4v9Fk96QOpkIrssI",2592000]";}',
'PHPSESSID' => 'abe468adef98b859d2100b97cb6da127',
'_csrf' => '542d3bc58acd73dd28aadc1e388c74c2697098a4c8d8bb4b855417ada2ebe4ffa:2:{i:0;s:5:"_csrf";i:1;s:32:"WuyFwYI342Jz0wAZfKr8kCX9vLqiS1Ri";}',
];
$_SESSION = [
'__flash' => [],
'__id' => 22727,
'__authKey' => 'gkEvlaqhpnAtz8mz4v9Fk96QOpkIrssI',
'__expire' => 1543857954,
'__captcha/site/captcha' => 'lesafiq',
'__captcha/site/captchacount' => 1,
];
Вот модель ShopPromoItem.php:
Код: Выделить всё
<?php
namespace appmodels;
use apphelpersBalanceHelper;
use appmodelsUser;
use appmodelsUserBalance;
use yiidbActiveRecord;
use yiihelpersHtml;
use yiihelpersJson;
class ShopPromoItem extends ActiveRecord
{
const STATUS_ENABLED = 'enabled';
const STATUS_DISABLED = 'disabled';
const STATUS_DELETED = 'deleted';
public static function tableName()
{
return '{{%shop_promo_item}}';
}
public function rules()
{
return [
];
}
public function attributeLabels()
{
return [
'status' => 'Статус',
];
}
public static function get($id)
{
$item = ShopPromoItem::findOne($id);
$class = '@app/models/' . $item->class;
return $class::findOne($id);
}
public function getTitle()
{
return Html::encode($this->title);
}
public function getPriceArray()
{
return Json::decode($this->price);
}
public function getPriceString()
{
$prices = $this->getPriceArray();
$result = '';
foreach ($prices as $currency => $price) {
$result .= '<img src="/images/' . $currency . '.png" style="vertical-align: middle; width: 24px;"> ' . BalanceHelper::convertToDigits($price);
}
return $result;
}
public function giveTo(User $user)
{
}
}
Вот ShopPromoItemBuyForm.php:
Код: Выделить всё
<?php
namespace appmodelsforms;
use apphelpersBalanceHelper;
use apphelpersRefererHelper;
use apphelpersSettingHelper;
use appmodelsShopPromoItem;
use appmodelsUser;
use appmodelsUserPromo;
use appmodelsUserBalance;
use appmodelsUserOperation;
use yiivalidatorsIpValidator;
class ShopPromoItemBuyForm extends UserPromo
{
public $item_id;
public function rules()
{
return [
['item_id', 'required'],
['item_id', 'integer'],
['item_id', 'exist',
'targetClass' => 'appmodelsShopPromoItem',
'targetAttribute' => 'id',
'filter' => ['status' => ShopPromoItem::STATUS_ENABLED]
],
['name', 'multProtect']
];
}
public function scenarios()
{
return [
self::SCENARIO_DEFAULT => ['name']
];
}
public function multProtect()
{
return;
// disable for debug mode
if (YII_DEBUG)
return;
// check evercookie
if (isset($_COOKIE['was_promo']) && $_COOKIE['was_promo'] == "true") {
$this->addError('name', Yii::t('app', 'Вы уже заказывали сайт с таким названием на проекте, повторный заказ сайта с таким именем запрещён'));
}
$validator = new IpValidator();
if ($validator->validate(Yii::$app->request->userPromoIP)) {
$ip = Yii::$app->request->userPromoIP;
$userPromo = UserPromo::find()->where(['id' => $ip])->limit(1)->one();
if ($userPromo !== null) {
$this->addError('name', Yii::t('app', 'Вы уже заказывали сайт с таким названием на проекте, повторный заказ сайта с таким именем запрещён'));
}
} else {
$this->addError('name', Yii::t('app', 'Вы уже заказывали сайт с таким названием на проекте, повторный заказ сайта с таким именем запрещён'));
}
}
public function buy(User $user)
{
if (!$this->validate()) {
Yii::$app->getSession()->setFlash('warning', implode('<br />', $this->getFirstErrors()));
return false;
}
if (Yii::$app->mutex->acquire('balance_' . $user->id)) {
Yii::$app->db->transaction(function() use ($user) {
$item = ShopPromoItem::get($this->item_id);
$prices = $item->getPriceArray();
// check balance
foreach ($prices as $currency => $price) {
if (!$user->balance->has($currency, BalanceHelper::convertToDigits($price))) {
Yii::$app->getSession()->setFlash('warning', Yii::t('app', 'Недостаточно средств на балансе'));
return false;
}
}
// decrease balance
foreach ($prices as $currency => $price) {
$user->balance->decrease($currency, BalanceHelper::convertToDigits($price));
$user->operation->create(UserOperation::OPERATION_SHOP_PROMO_BUY, $currency, BalanceHelper::convertToDigits($price), [
'ShopPromoItem_id' => $this->item_id
]);
}
$item->giveTo($user);
// give reward to referer
RefererHelper::giveReward($user, UserBalance::CURRENCY_USD, BalanceHelper::convertToDigits($prices['usd']));
$message = '';
foreach ($prices as $currency => $price) {
$message .= Yii::t('app', '{sum} долларов', ['sum' => BalanceHelper::convertToDigits($price)]);
}
Yii::$app->getSession()->setFlash('success', Yii::t('app', 'Вы купили «{title}»', ['title' => Yii::t('app', $item->getTitle())]) .
'<br />' . Yii::t('app', 'Потрачено {price}', ['price' => $message]));
return true;
});
}
}
}
UserPromo.php:
Код: Выделить всё
<?php
namespace appmodels;
use yiidbActiveRecord;
use yiihelpersHtml;
class UserPromo extends ActiveRecord
{
const STATUS_ENABLED = 'enabled';
const STATUS_DISABLED = 'disabled';
const STATUS_DELETED = 'deleted';
public static function tableName()
{
return '{{%user_promo}}';
}
public function rules()
{
return [
['id', 'exist'],
['user_id', 'integer'],
['name', 'required'],
['name', 'filter', 'filter' => 'trim'],
['name', 'match', 'pattern' => '#^[w_-]+$#i'],
['name', 'unique', 'targetClass' => self::className(), 'message' => Yii::t('app', 'Указанное название для вашего сайта уже занято')],
['name', 'string', 'min' => 2, 'max' => 255],
];
}
public function attributeLabels()
{
return [
'status' => 'Статус',
'name' => Yii::t('app', 'Название'),
];
}
public static function findIdentity($id)
{
$identity = static::findOne(['id' => $id]);
return $identity;
}
public static function findByName($name)
{
return static::findOne(['name' => $name]);
}
public function getName()
{
return Html::encode($this->name);
}
public function getPromo()
{
return $this->hasOne(Promo::className(), ['id' => 'promo_id']);
}
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public function getTitle()
{
return $this->promo->getTitle();
}
public function getType()
{
return $this->promo->getType();
}
public function getProfit($type)
{
return $this->promo->{$type . '_profit'};
}
}
PromoSiteShopItem.php:
Код: Выделить всё
<?php
namespace appmodels;
use apphelpersBalanceHelper;
use apphelpersSettingHelper;
class PromoSiteShopItem extends ShopPromoItem
{
public function giveTo(User $user)
{
(new UserPromo([
'user_id' => $user->id,
'promo_id' => 21,
'created_at' => time(),
'status' => UserPromo::STATUS_ENABLED
]))->save(false);
$prices = $this->getPriceArray();
// increase reserve
$value = SettingHelper::get('reserve.promo.sum') + intval(BalanceHelper::convertToDigits($prices['usd']) / 100 * 50);
SettingHelper::set('reserve.promo.sum', $value);
}
}
Promo.php:
Код: Выделить всё
<?php
namespace appmodels;
use yiidbActiveRecord;
use yiihelpersHtml;
class Promo extends ActiveRecord
{
const TYPE_PROMO = 'promo';
const STATUS_ENABLED = 'enabled';
const STATUS_DISABLED = 'disabled';
const STATUS_DELETED = 'deleted';
public static function tableName()
{
return '{{%promo}}';
}
public function rules()
{
return [
['user_id', 'integer'],
];
}
public function attributeLabels()
{
return [
'status' => 'Статус',
];
}
public function getType()
{
return $this->type;
}
public function getTitle()
{
return Html::encode($this->title);
}
}
Контроллер:
Код: Выделить всё
<?php
namespace appcontrollersusermainservices;
use appcomponentsController;
use appmodelsShopPromoItem;
use appmodelsformsShopPromoItemBuyForm;
use yiifiltersAccessControl;
use yiiwebForbiddenHttpException;
use yiifiltersVerbFilter;
use yiihelpersUrl;
use appmodelsUserPromo;
class PromoController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@'],
],
],
],
];
}
public function beforeAction($action)
{
if (Yii::$app->params['user']['promo']['temporaryDisabled']) {
throw new ForbiddenHttpException('Заказ временно приостановлен');
}
return parent::beforeAction($action);
}
public function actionIndex()
{
$this->layout = 'page';
$items = ShopPromoItem::find()->where([
'status' => ShopPromoItem::STATUS_ENABLED
])->all();
$model = new ShopPromoItemBuyForm();
if ($model->load(Yii::$app->request->post())) {
$model->buy(Yii::$app->user->identity);
}
$promo = UserPromo::find()->where([
'user_id' => Yii::$app->user->identity->id,
'status' => UserPromo::STATUS_ENABLED
])->with('promo')->orderBy('promo_id DESC')->all();
return $this->render('index', [
'items' => $items,
'model' => $model,
'promo' => $promo,
]);
}
}