Не получается отправить и найти запрос в базе данных Class 'app\models\' not found?

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
swallow
Сообщения: 5
Зарегистрирован: 2018.12.04, 09:58

Не получается отправить и найти запрос в базе данных Class 'app\models\' not found?

Сообщение swallow »

Здравстуйте, столкнулась с такой проблемой, некий запрос "name" который ввёл пользователь не сохраняется в базе данных да ещё и вылетает эта глупая ошибка с которой вообще не могу управиться.. видимо я глупее неё..подскажите пожалуйста в чём загвоздка?

Вот данная ошибка в полном формате:

Код: Выделить всё

PHP Fatal Error – yii\base\ErrorException
Class 'app\models\' 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. yii\base\ErrorHandler::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 app\models;
 
use app\helpers\BalanceHelper;
use app\models\User;
use app\models\UserBalance;
use yii\db\ActiveRecord;
use yii\helpers\Html;
use yii\helpers\Json;
 
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 app\models\forms;
 
use app\helpers\BalanceHelper;
use app\helpers\RefererHelper;
use app\helpers\SettingHelper;
use app\models\ShopPromoItem;
use app\models\User;
use app\models\UserPromo;
use app\models\UserBalance;
use app\models\UserOperation;
use yii\validators\IpValidator;
 
class ShopPromoItemBuyForm extends UserPromo
{
    public $item_id;
 
    public function rules()
    {
        return [
            ['item_id', 'required'],
            ['item_id', 'integer'],
            ['item_id', 'exist',
                'targetClass' => '\app\models\ShopPromoItem',
                '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 app\models;
 
use yii\db\ActiveRecord;
use yii\helpers\Html;
 
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 app\models;
 
use app\helpers\BalanceHelper;
use app\helpers\SettingHelper;
 
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 app\models;
 
use yii\db\ActiveRecord;
use yii\helpers\Html;
 
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 app\controllers\user\main\services;
 
use app\components\Controller;
use app\models\ShopPromoItem;
use app\models\forms\ShopPromoItemBuyForm;
use yii\filters\AccessControl;
use yii\web\ForbiddenHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Url;
 
use app\models\UserPromo;
 
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,
        ]);
    }
}
Аватара пользователя
yiijeka
Сообщения: 3103
Зарегистрирован: 2012.01.28, 09:14
Откуда: Беларусь
Контактная информация:

Re: Не получается отправить и найти запрос в базе данных Class 'app\models\' not found?

Сообщение yiijeka »

В models/ShopPromoItem.php в строке 40
вместо $class = 'app\\models\\' . $item->class; напишите $class = '\app\models\' . $item->class;
Это раз.
Два - это у вас $item->class может быть NULL, поэтому дальше может не выполнится return $class::findOne($id);, т.е возникает эта ошибка, что вы озвучили. Нужно обработать случай когда $item->class === NULL
swallow
Сообщения: 5
Зарегистрирован: 2018.12.04, 09:58

Re: Не получается отправить и найти запрос в базе данных Class 'app\models\' not found?

Сообщение swallow »

yiijeka писал(а): 2018.12.04, 16:03 В models/ShopPromoItem.php в строке 40
вместо $class = 'app\\models\\' . $item->class; напишите $class = '\app\models\' . $item->class;
Это раз.
Два - это у вас $item->class может быть NULL, поэтому дальше может не выполнится return $class::findOne($id);, т.е возникает эта ошибка, что вы озвучили. Нужно обработать случай когда $item->class === NULL
Спасибо вам огромное!!!
Ответить