zoukankan      html  css  js  c++  java
  • yii框架基本操作

    <?php
    
    namespace appcontrollers;
    
    use yiiwebController;
    use appmodelsDemoForm;
    use appmodelsCountry;
    
    /**
     * 该示例文件包含 cookies session  request  response 等
     * 示例代码 
     * @author timeless
     */
    class DemoController extends Controller {
    
        /**
         * yii框架默认控制器的操作根普通的方法使用是有区别的   开头是使用action 
         * @access public
         * @param string $message  
         * 当应用接收到请求并确定由 say 操作来响应请求时,应用将从请求的参数中寻找对应值传入进来
         */
        public function actionSay($message = 'hello') {
    //        echo $message;
            return $this->render('say', ['message' => $message]);
        }
    
        /**
         * 测试Forms 
         */
        public function actionEntry() {
            $model = new DemoForm();
            if ($model->load(Yii::$app->request->post()) && $model->validate()) {
                return $this->render('entry-confirm', ['model' => $model]);
            } else {
                // 无论是初始化显示还是数据验证错误
                //其实数据首先由客户端 JavaScript 脚本验证,
                //然后才会提交给服务器通过 PHP 验证。
                //yiiwidgetsActiveForm 足够智能到把你在
                //EntryForm 模型中声明的验证规则转化成
                //客户端 JavaScript 脚本去执行验证。
                return $this->render('entry', ['model' => $model]);
            }
        }
    
        /**
         * 测试数据库
         * db.php配置的数据库连接可以在应用中通过 Yii::$app->db 表达式访问
         * config/db.php 将被包含在应用配置文件 config/web.php 中,
         * 后者指定了整个应用如何初始化。请参考配置章节了解更多信息。
         */
        public function actionDbmanage() {
            $countries = Country::find()->orderBy('name')->all();
    //        print_r($countries);
            var_dump($countries);
        }
    
        /**
         * 测试 request请求
         * @access public
         */
        public function actionTestrequest() {
            //获取 请求信息
            $request = yii::$app->request;
            echo $request->get('id', '');
            var_dump($request->ispost);
            var_dump($request->isget);
            echo $request->UserIp;
            if ($request->isAjax) { /* 该请求是一个 AJAX 请求 */
            }
            if ($request->isGet) { /* 请求方法是 GET */
            }
            if ($request->isPost) { /* 请求方法是 POST */
            }
            if ($request->isPut) { /* 请求方法是 PUT */
            }
        }
    
        /*     * response 响应************************************************************************************** */
    
        /**
         * 测试 response  响应
         * @access public
         */
        public function actionTestresponse() {
            $res = yii::$app->response;
            //如果需要指定请求失败,可抛出对应的HTTP异常,如下所示:
            throw new yiiwebNotFoundHttpException;
    //        yiiwebBadRequestHttpException: status code 400.
    //        yiiwebConflictHttpException: status code 409.
    //        yiiwebForbiddenHttpException: status code 403.
    //        yiiwebGoneHttpException: status code 410.
    //        yiiwebMethodNotAllowedHttpException: status code 405.
    //        yiiwebNotAcceptableHttpException: status code 406.
    //        yiiwebNotFoundHttpException: status code 404.
    //        yiiwebServerErrorHttpException: status code 500.
    //        yiiwebTooManyRequestsHttpException: status code 429.
    //        yiiwebUnauthorizedHttpException: status code 401.
    //        yiiwebUnsupportedMediaTypeHttpException: status code 415.
    //        如果想抛出的异常不在如上列表中,可创建一个yiiwebHttpException异常,带上状态码抛出,如下:
    //        throw new yiiwebHttpException(402);
        }
    
        /**
         * response 响应格式化  
          yiiwebResponse::FORMAT_HTML: 通过 yiiwebHtmlResponseFormatter 来实现.
          yiiwebResponse::FORMAT_XML: 通过 yiiwebXmlResponseFormatter来实现.
          yiiwebResponse::FORMAT_JSON: 通过 yiiwebJsonResponseFormatter来实现.
          yiiwebResponse::FORMAT_JSONP: 通过 yiiwebJsonResponseFormatter来实现.
         * @access public
         */
        PUBLIC function actionTestresponseformat() {
            $response = Yii::$app->response;
    //        $response->format = yiiwebResponse::FORMAT_JSON;
    //        return ['message' => 'hello world'];   //返回json数据
    //        $response->format = yiiwebResponse::FORMAT_HTML;
    //        return 'DSADASDA';   //返回HTML数据
            $response->format = yiiwebResponse::FORMAT_XML;
            return ['message' => 'hello world'];   //返回XML数据
        }
    
        /**
         * 跳转实现 响应
         * @access public
         */
        public function actionRedirect() {
            return $this->redirect('http://example.com/new', 301);
        }
    
        /**
         *  文件下载
         * @access public
         */
        public function actionDownload() {
            return Yii::$app->response->sendFile(__DIR__ . '/../a.txt');
    //            yiiwebResponse::sendFile(): 发送一个已存在的文件到客户端
    //    yiiwebResponse::sendContentAsFile(): 发送一个文本字符串作为文件到客户端
    //    yiiwebResponse::sendStreamAsFile(): 发送一个已存在的文件流作为文件到客户端
        }
    
        /** 响应response************************************************* */
    
        /** session响应************************************************* */
        public function actionSessiondemo() {
            $session = yii::$app->session;
            //var_dump($session->isActive);
            //$session->open();
            //$session->close();
            //$session->destory();
            // Flash数据是一种特别的session数据,它一旦在某个请求中设置后,只会在下次请求中有效,然后该数据就会自动被删除。 常用于实现只需显示给终端用户一次的信息,如用户提交一个表单后显示确认信息。
            // 请求 #1
            // 设置一个名为"postDeleted" flash 信息
            $session->setFlash('postDeleted', 'You have successfully deleted your post.');
            // 请求 #2
            // 显示名为"postDeleted" flash 信息
            echo $session->getFlash('postDeleted');
            // 请求 #3
            // $result 为 false,因为flash信息已被自动删除
            $result = $session->hasFlash('postDeleted');
    //        当调用yiiwebSession::setFlash()时, 会自动覆盖相同名的已存在的任何数据,
    //        为将数据追加到已存在的相同名flash中,可改为调用yiiwebSession::addFlash()。 例如
            // 请求 #1
            // 在名称为"alerts"的flash信息增加数据
            $session->addFlash('alerts', 'You have successfully deleted your post.');
            $session->addFlash('alerts', 'You have successfully added a new friend.');
            $session->addFlash('alerts', 'You are promoted.');
            // 请求 #2
            // $alerts 为名为'alerts'的flash信息,为数组格式
            $alerts = $session->getFlash('alerts');
        }
    
        /*     * cookies操作********************************************** */
    
        public function actionCookiesdemo() {
            //写入的时候是响应  读取的时候是请求
            $res_cookies = yii::$app->response->cookies;
            //键name  值 value
            $res_cookies->add(new yiiwebCookie(['name' => 'language', 'value' => 'zhuang']));
            $res_cookies->remove('language');  //或者直接 unset($_COOKIES['language'])
            $req_cookies = yii::$app->request->cookies;
            echo $req_cookies->getValue('language', 'null呀');
        }
    
    }
  • 相关阅读:
    python-day49--前端 css-层叠样式表
    python-day49--前端 html
    python-day48--mysql之视图、触发器、事务、存储过程、函数
    python-day47--pymysql模块
    python-day47--mysql数据备份与恢复
    python-day46--前端基础之html
    python-day45--mysql索引
    window系统下远程部署Tomcat
    tomcat下部署应用helloworld
    tomcat配置文件context.xml和server.xml分析
  • 原文地址:https://www.cnblogs.com/timelesszhuang/p/4893397.html
Copyright © 2011-2022 走看看