前言:小编用的是wafer2 node.施工方案下边连接有情况安排及搭建流程() ,连接是法定的能够点击
有关 Nodejs,相信看那篇的小说的同伴已经明白了无数,有生机勃勃对了 Nodejs 根底。可是 Nodejs 怎么样采纳,怎么样用 Nodejs 搭建在服务器上,小编想非常多友人想明白,在这地享受小编的心得心得,希望对你的劳作学习抱有利于。 服务器的搭建有好种种,比如 Java,PHP,而作者首推Node.js。为何?因为快。Node.js 入门快,比较别的语言更便于步向后台的世界;安装快,配置不难;命令轻易命理术数。不过对于众多童鞋来讲,学习了 Node.js 的基本功知识,却不亮堂该怎么利用 Node.js ,如何奉行。
此次作者就推来推去童鞋急迅入门,尽快接受起 Node.js,在实战中学习 Node.js,对工学都有更加好的支持。
1、利用基于 Node.js 的 Express 神速搭建项目。
2、介绍 Express 项目构造。
3、学习怎么着连接 MongoDB 数据库,利用 Node.js 操作 MongoDB 数据库。
4、Express 的体系是 .jade 页面,怎样改为 .html 页面。
5、学习怎么校勘目录构造,使其能够在切实地工作的种类中采取
1.施用 Nodejs 连忙搭建项目
先是安装 Express
npm install express-generator -g
用Express快速转移项目
express demo
cd demo
npm install
运营项目,检查评定是还是不是搭建设成功
npm run start
在浏览器张开http://localhost:3000 ,这么些地方是Express快捷搭建项目暗中认可之地址,在bin目录下的www文件里,如图
信用合作社Wechat截图_ef9c5153-4d13-463c-94e7-be4170e11f7a.png
花色搭建完结,是否非常快。那正是自己心爱得舍不得甩手Node的位置
要开创 Zend 项目,首先要下载并解压 Zend Framework。
原来的作品地址
enter image description here
下载最新的 Zend Framework 1.12.20 源码包,(大家选择的是 Zend Framework 1,所以下边包车型客车剧情都是基于 Zend 1卡塔 尔(阿拉伯语:قطر
解压到杰出的地点(比方:/home/xxx/bin/卡塔尔国.
注: /home/xxx/bin
是本人偏疼的目录,假如您设定了协和的目录,就应有替换上面忘其所以中相应之处
$ tar -xzvf ZendFramework-1.12.20.tar.gz -C /home/xxx/bin
这么 Zend Framework 就设置在了 /home/xxx/bin/ZendFramework-1.12.20
注1:Zend Framework
各样版本下载
注2:$
符号表示近些日子境遇是 Linux 命令行终端,在等候输入壹人命令。
mongoose是豆蔻梢头款基于nodejs的高雅数据营造mongodb模型工具。mongodb是豆蔻年华款新型的json(键值对卡塔尔数据类型的数额存款和储蓄格式的数据库。在近些日子来讲,使用nodejs和mongodb是为中型Mini型公司以至个人web开拓的绝佳的配置。
意气风发、配置mysql 数据库连接参数
开辟终端,运维命令
npm install mongolass -s
在bin目录下加多文件,mongo_base.js,里面包车型大巴代码如下
const Mongolass = require('mongolass');
const mongolass = new Mongolass();
exports.db = { mongolass: mongolass };
const db = exports.db;
let connected = [];
exports.OnConnected = function (fn) {
if (fn) {
connected.push(fn);
}
};
//'mongodb://localhost:27017/testdb'
exports.connectDB = function (conn) {
return mongolass.connect(conn).then(function () {
//================USER RELATED==================
db.test = mongolass.model('test', {
name:{type:'string'},
});
db.test.insert({name:'test'}).exec()
connected.forEach(function (oneFn) {
if (oneFn) {
oneFn();
}
});
});
};
在www文件里加多代码
require('./mongo_base').connectDB('mongodb://localhost:27017/testdb');
小编们的MongDB连接成功。 运维Computer的MongDB,然后重启项目。 下边检查是还是不是咱们成功了。 展开终端,然后运营命令,步向到mongdb。
mongo
下一场运营命令,查看是或不是加多上数据库testdb
show dbs
enter image description here
好了,我们的门类MongoDB数据库加多实现。
在 Zend 安装目录下的 bin/ 目录下有 zf.sh 脚本文件,你要求在系统path目录下创建该公文的链接,然后就能够在指令行中任哪个地方方使用zf命令创制项目了。
$ sudo ln -s /home/xxx/bin/ZendFramework-1.12.20/bin/zf.sh /usr/local/bin/zf
开垦命令行(Ctrl Alt T),切换来你想成立项目标地点,若是你想在 ~/demo/
目录下创办 Zend 项目:cd ~/demo/
。
试行下边的指令成立 quickstart 项目:
$ zf create project quickstart
那般就创制了 /home/xxx/demo/quickstart,并且在 quickstart 目录下自行成立了 Zend 项目标有个别索引布局。其种类组织如下:
quickstart
|-- application
| |-- Bootstrap.php
| |-- configs
| | `-- application.ini
| |-- controllers
| | |-- ErrorController.php
| | `-- IndexController.php
| |-- models
| `-- views
| |-- helpers
| `-- scripts
| |-- error
| | `-- error.phtml
| `-- index
| `-- index.phtml
|-- library
|-- public
| |-- .htaccess
| `-- index.php
`-- tests
|-- application
| `-- bootstrap.php
|-- library
| `-- bootstrap.php
`-- phpunit.xml
当时,只是创设了 Zend 项目组织,你还须要把 Zend Framework 增加到 quickstart 项目中,有三种艺术,第一中学是开创三个链接,把 zend 框架下的 library 目录链接到 quickstart/library ,另生龙活虎种艺术是平素复制 zend 框架下的 library 目录替换掉 quickstart/library。
# Symlink
$ cd library
$ ln -s /home/xxx/bin/ZendFramework-1.12.20/library/Zend .
# or copy
$ cd library
$ cp -r /home/xxx/bin/ZendFramework-1.12.20/library/Zend .
那般就足以看看 quickstart/library/Zend 目录了。
打开 server下面的config.js
步入根目录,输入指令
npm install ejs -s
找到根目录下的app.js,参预代码
var ejs = require('ejs'); //引入的ejs插件
app.engine('html', ejs.__express);//设置html引擎
app.set('view engine', 'html');//设置视图引擎
在app.js里,去掉代码
app.set('view engine', 'jade');
重启服务,在view里加多html页面,同一时间在routes里依旧在app.js里增多调控器,就足以访谈html文件了。实例代码如下,在浏览器访谈http://localhost:3000/b
enter image description here
Bootstrap 类定义了 Zend 项目运转时要开始化的能源和组件。暗中认可地,Zend Framework 开始化了 Front Controller,然后它使用 application/controllers/ 作为搜索 action controller 的私下认可路线。那个类如下:
// application/Bootstrap.php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
}
如您所见,那其间未有怎么内容。
user 私下认可都是 'root'
在这里个项目中大家想以mvc的形式开辟。那么哪些订正目录呢,能够直达大家的目标。上面注意本身说的,新建目录和新建文件,不要弄混。
1.首先新建目录,auth,把地点的建的mongo_base.js放在此个目录里。然后新建文件index.js,代码如下
let MG = require('./mongo_base.js');
exports.db = MG.db;
exports.connectDB = MG.connectDB;
exports.OnConnected = MG.OnConnected;
2.改善bin目录下www文件里的有关mongo_base.js的引进调用。改后如下
enter image description here
3.在routes下新建七个目录controller,db。
把index.js、users.js放在controller的目录里。请精心改良app.js代码里关于那八个文本的门路引进。
4.在db目录下新建文件user.js。用于在数据仓库储存款和储蓄顾客。校正后目录如下图。
enter image description here
5.在user.js里编写代码
const db = require('../../auth').db;
exports.OnConnected = require('../../auth').OnConnected;
const onConnect = function () {
const mongolass = db.mongolass;
//===============DEVICE RELATED==================
// socket.io room. Connect it with `http://{server}/{roomId}`
db.user = mongolass.model('user', {
nickname:{type:'string'},
});
};
exports.OnConnected(onConnect);
exports.db = db;
6.更动controller下的index.js,矫正后如下
var express = require('express');
var router = express.Router();
const MG = require('../db/user');
let dbTable;
MG.OnConnected(function () {
dbTable = MG.db.user;
});
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/test', function(req, res, next) {
return dbTable.insert({nickname:'abc'}).exec().then(function () {
res.send('存储成功');
})
});
module.exports = router;
7.双重启航项目,在浏览器中输入http://localhost:3000/test ,如下图!
enter image description here
暗中同意配置文件放在:application/configs/application.ini,蕴涵部分着力的通令,比如设置php景况,设置运维类,设置 action controller 等。文件内容如下:
; application/configs/application.ini
[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
[staging : production]
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
有关那几个文件有多少个要点:
(1) 使用 ini 配置文件时,你能够直接引用常量,APPLICATION_PATH 正是贰个常量。
(2) 这么些文件被分成多少个部分:production,staging,testing 和 development。前面几个包含了 production 的安装。区别的景况其布署分开,那样有助于开辟和调节和测量试验。
在尖峰根目录下输入
brew install mongodb
现身上边情状注解安装成功,安装的目录正是
/usr/local/Cellar/mongodb/3.2.10
。
db 为总是是多少库名
那篇随笔每写一步,笔者都会自个儿运维,希望观望那篇小说的童鞋可以入门express的实战,并在实战中开创和煦的构造。
应用程序的 action controller 定义了程序流程,把客户诉求映射到万分的 model 和 view。
多少个 action controller 应包罗一个或两个以Action终极的点子,那几个方式能够通过 web 央求访谈到。默许地,Zend Framework U悍马H2Ls 固守 /controller/action 的方式,个中 controller 就映射 action controller 名字(以Controller作为后缀卡塔 尔(阿拉伯语:قطر,而 action 就映射到 action 方法(以Action作为后缀卡塔尔国。
平凡,供给一个 IndexController,它象征网址首页,和一个ErrorController,它意味着诸如 HTTP404、HTTP500 等不当页面.
初阶 IndexController 代码如下:
// application/controllers/IndexController.php
class IndexController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
}
}
初始 ErrorController 代码如下:
// application/controllers/ErrorController.php
class ErrorController extends Zend_Controller_Action
{
public function errorAction()
{
$errors = $this->_getParam('error_handler');
switch ($errors->type) {
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
// 404 error -- controller or action not found
$this->getResponse()->setHttpResponseCode(404);
$this->view->message = 'Page not found';
break;
default:
// application error
$this->getResponse()->setHttpResponseCode(500);
$this->view->message = 'Application error';
break;
}
$this->view->exception = $errors->exception;
$this->view->request = $errors->request;
}
}
首先次开行服务端,这里供给做一些备选工作.
mkdir -p /data/db
nano ~/.bash_profile
//添加mongodb安装目录到环境变量中
export PATH=/usr/local/Cellar/mongodb/3.2.10/bin:${PATH}
//然后覆盖保存
source ~/.bash_profile
是因为Mac暗许不突显隐瞒文件,所以向来找文件夹是找不到的。要选用上边得意忘形显示隐瞒文件
defaults write com.apple.finder AppleShowAllFiles -boolean true ; killall Finder//显示
defaults write com.apple.finder AppleShowAllFiles -boolean false ; killall Finder//隐藏
计划文件改正后
systemLog:
destination: file
path: /usr/local/var/log/mongodb/mongo.log
logAppend: true
storage:
dbPath: data/db
net:
bindIp: 127.0.0.1
修改
dbPath
为大家偏巧创立的文书夹data/db
,借使筹划连接非本地遭逢的mongodb数据库时,bind_ip = 0.0.0.0 即可.
sudo chown `id -u` /data/db
mongod
ok,mongodb 服务端终于运行起来了。
pass 暗许为小程序应用软件ID
Zend Framework 中的 Views 是用平常 PHP 代码写的。View scripts 在 application/views/scripts/ 上边,它以调节器名字分文件夹组织起来。本例中,大家有叁个 IndexController 和 ErrorController,因而相应地,也应在 View scripts 目录下有 index/ 和 error/ 子目录。在此个子目录中,又有每种 view scripts 文件,对应 Controller 中的 Action。本例中,使用 index/index.phtml 和 error/error.phtml。
上边是暗中认可的 index/index.phtml view script:
<!-- application/views/scripts/index/index.phtml -->
<style>
a:link,
a:visited
{
color: #0398CA;
}
span#zf-name
{
color: #91BE3F;
}
div#welcome
{
color: #FFFFFF;
background-image: url(http://framework.zend.comkg_header.jpg);
width: 600px;
height: 400px;
border: 2px solid #444444;
overflow: hidden;
text-align: center;
}
div#more-information
{
background-image: url(http://framework.zend.comkg_body-bottom.gif);
height: 100%;
}
</style>
<div id="welcome">
<h1>Welcome to the Zend Framework!<h1 />
<h3>This is your project's main page<h3 />
<div id="more-information">
<p>
<img src="http://framework.zend.comPoweredBy_ZF_4LightBG.png" />
</p>
<p>
Helpful Links: <br />
<a href="http://framework.zend.com/">Zend Framework Website</a> |
<a href="http://framework.zend.com/manual/en/">Zend Framework
Manual</a>
</p>
</div>
</div>
error/error.phtml 微微复杂一点,当中使用了php条件语句:
<!-- application/views/scripts/error/error.phtml -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN";
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Zend Framework Default Application</title>
</head>
<body>
<h1>An error occurred</h1>
<h2><?php echo $this->message ?></h2>
<?php if ('development' == $this->env): ?>
<h3>Exception information:</h3>
<p>
<b>Message:</b> <?php echo $this->exception->getMessage() ?>
</p>
<h3>Stack trace:</h3>
<pre><?php echo $this->exception->getTraceAsString() ?>
</pre>
<h3>Request Parameters:</h3>
<pre><?php echo var_export($this->request->getParams(), 1) ?>
</pre>
<?php endif ?>
</body>
</html>
设置可视化学工业具Robomongo。
对于 quickstart 项目,大家把它坐落于 apache 服务器上运维。
我们须要设置二个设想主机,那样就能够在浏览器中输入域名来访问大家的网址了。假若你曾经安顿好了 php apache mysql 运维碰到,若无,请仿效教程
风华正茂经我们的品种所映射的域名是:quickstart.local。
步入 apache 配置目录,成立构造文件:
cd /etc/apache2/sites-available/
sudo gedit quickstart.local.conf
然后复制下边包车型客车内容到该配置文件,注意:项目路径必要替换来你自个儿的品种路径:
<VirtualHost *:80>
ServerName quickstart.local
ServerAdmin webmaster@localhost
DocumentRoot /home/xxx/demo/quickstart/public
<Directory /home/xxx/demo/quickstart/public>
AllowOverride all
require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
封存该文件,并且启用该配置:sudo a2ensite quickstart.local
下一场打开hosts文件:sudo gedit /etc/hosts
增多豆蔻梢头行:
127.0.0.1 quickstart.local
末尾重启一下 apache 服务器:
sudo service apache2 restart
到此结束,那一个项目就创办成功还要可运维了。
mongodb和nodejs的模块包不等同,它是应用c 编写的跨平台数据库,可以在官方网站(见参谋资料卡塔尔国下载安装,本次安装以window 32bit为例:
注意这里有个坑:host开辟情形下要填localhost,不要填分配给你的域名,笔者就手贱的改造了那边,结果找了1个钟头才找到难点由来
今昔就能够访问你的种类网址了,展开浏览器输入http://quickstart.local
,就能够观察迎接页了。
下载之后解压该安装包到您想要的目录,重命名字为mongodb,如图:
chmod -R 777 /home/xxx/demo/quickstart
试试看。开采mongodb文件夹,新建一个data文件夹用于存款和储蓄数据库,当然也得以钦点其余目录。
二、Hello World
你可能注意到,上边的 view scripts 不是完整的 html 页面,那是假意设计的。大家只想让 action 只回去 action 自己要出口的内容,并不是整整应用程序页面。
最近来构成七个完完全全的 HTML 页面。我们接受一个大局的 layout 来作为网址联合的体制。
注: 上边包车型大巴下令若无表达,暗中同意是在近日项目根目录下推行的。
起来选用 Zend_Layout
,首先让 bootstrap 来加载 Layout
财富。通过上边包车型客车吩咐可达成:
$zf enable layout
# Layouts have been enabled, and a default layout created at
# application/layouts/scripts/layout.phtml
# A layout entry has been added to the application config file.
此时,application/configs/application.ini 内容自动更新了:
; application/configs/application.ini
; Add to [production] section:
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
本条命令告诉应用程序去 application/layouts/scripts 去寻找 layout。
我们还要启用 XHTML DocType 评释,为此,在 bootstrap 中加载该能源。在 bootstrap中增添财富的最简便的措施正是创办一个以init开端的不二秘籍。那时,我们利用 _initDoctype() 方法来伊始化 doctype:
// application/Bootstrap.php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initDoctype()
{
}
}
有了这么些主意,还供给让 view 使用正确的 doctype,不过 view 从哪个地方来?最简易的主意正是初步化 View 能源;有了它,就能够把 view 对象归入 bootstrap 并接纳它。
加多下行到 aplication/configs/application.ini 来成立 view 资源:
; application/configs/application.ini
; Add to [production] section:
resources.view[] =
接下来再来充实一下 _initDoctype() 方法。
// application/Bootstrap.php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initDoctype()
{
$this->bootstrap('view');
$view = $this->getResource('view');
$view->doctype('XHTML1_STRICT');
}
}
然后,创设全局的 layout:
<!-- application/layouts/scripts/layout.phtml -->
<?php echo $this->doctype() ?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Zend Framework Quickstart Application</title>
<?php echo $this->headLink()->appendStylesheet('/css/global.css') ?>
</head>
<body>
<div id="header" style="background-color: #EEEEEE; height: 30px;">
<div id="header-logo" style="float: left">
<b>ZF Quickstart Application</b>
</div>
<div id="header-navigation" style="float: right">
<a href="<?php echo $this->url(
array('controller'=>'guestbook'),
'default',
true) ?>">Guestbook</a>
</div>
</div>
<?php echo $this->layout()->content ?>
</body>
</html>
使用headLink()
来生成<link>
元素。
这几天再张开浏览器并查看源代码,应该能收看
XHTML尾部,<head> <title> <body>
等部分。
再打开mongodbbin文件夹,新建三个cmd文件,内容为:
mongod --dbpath "d:program filesmongodbdata"//自定义地址,内容为数据库文档存储文件夹。
先说一下文件布局
现行反革命考虑一下guestbook的三结合,它富含部分记录,每种记录由注释,时间戳,email地址等组合。咱们把它存在数据Curry,并有几个唯意气风发id。大家目的在于能保留、获取具有记录。
为此,二个归纳的 guestbook 模型 API 犹如上面那样:
// application/models/Guestbook.php
class Application_Model_Guestbook
{
protected $_comment;
protected $_created;
protected $_email;
protected $_id;
public function __set($name, $value);
public function __get($name);
public function setComment($text);
public function getComment();
public function setEmail($email);
public function getEmail();
public function setCreated($ts);
public function getCreated();
public function setId($id);
public function getId();
}
class Application_Model_GuestbookMapper
{
public function save(Application_Model_Guestbook $guestbook);
public function find($id);
public function fetchAll();
}
}
下边,我们得以起来构思什么设置数据库了。
首先要开头化 Db 能源。使用 zf configure db-adapter 命令:
zf configure db-adapter "adapter=Pdo_MySql&host=localhost&username=root&password=&dbname=guestbook" production
zf configure db-adapter "adapter=Pdo_MySql&host=localhost&username=root&password=&dbname=guestbook-test" testing
zf configure db-adapter "adapter=Pdo_MySql&host=localhost&username=root&password=&dbname=guestbook-dev" development
就算成功举办,那么在 application/configs/application.ini 中就能够看见新扩充的几行安顿:
//application/configs/application.ini
resources.db.adapter = "Pdo_MySql"
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = ""
resources.db.params.dbname ="guestbook"
注:要把数据库密码设置成你本人的。
下一场创制数据库,展开 phpMyadmin,创设数量库 guestbook,输入上面SQL语句并实践:
CREATE TABLE IF NOT EXISTS `guestbook` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(32) NOT NULL DEFAULT 'noemail@test.com',
`comment` varchar(200) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
接下去我们应用 Table Data
Gateway
机制来三番五次数据源。Zend_Db_Table
提供了那几个意义。
先是创设三个 Zend_Db_Table
类:
$ zf create db-table Guestbook guestbook
翻看项目布局,开掘多了一个 application/models/DbTable/ 目录,里面有多个 Guestbook.php 文件。其剧情如下:
// application/models/DbTable/Guestbook.php
/**
* This is the DbTable class for the guestbook table.
*/
class Application_Model_DbTable_Guestbook extends Zend_Db_Table_Abstract
{
/** Table name */
protected $_name = 'guestbook';
}
注意 Application_Model_DbTable
类前缀,它对应
application/models/DbTable 目录。
接下来创设叁个 Data Mapper。Data Mapper 映射对象到数据库。本例中,它将映射 model 到数据源。
$ zf create model GuestbookMapper
然后展开 application/models/GuestbookMapper.php 并输入以下内容:
// application/models/GuestbookMapper.php
class Application_Model_GuestbookMapper
{
protected $_dbTable;
public function setDbTable($dbTable)
{
if (is_string($dbTable)) {
$dbTable = new $dbTable();
}
if (!$dbTable instanceof Zend_Db_Table_Abstract) {
throw new Exception('Invalid table data gateway provided');
}
$this->_dbTable = $dbTable;
return $this;
}
public function getDbTable()
{
if (null === $this->_dbTable) {
$this->setDbTable('Application_Model_DbTable_Guestbook');
}
return $this->_dbTable;
}
public function save(Application_Model_Guestbook $guestbook)
{
$data = array(
'email' => $guestbook->getEmail(),
'comment' => $guestbook->getComment(),
'created' => date('Y-m-d H:i:s'),
);
if (null === ($id = $guestbook->getId())) {
unset($data['id']);
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data, array('id = ?' => $id));
}
}
public function find($id, Application_Model_Guestbook $guestbook)
{
$result = $this->getDbTable()->find($id);
if (0 == count($result)) {
return;
}
$row = $result->current();
$guestbook->setId($row->id)
->setEmail($row->email)
->setComment($row->comment)
->setCreated($row->created);
}
public function fetchAll()
{
$resultSet = $this->getDbTable()->fetchAll();
$entries = array();
foreach ($resultSet as $row) {
$entry = new Application_Model_Guestbook();
$entry->setId($row->id)
->setEmail($row->email)
->setComment($row->comment)
->setCreated($row->created);
$entries[] = $entry;
}
return $entries;
}
}
今昔,创立 model 类,依然使用 zf 命令:
$ zf create model Guestbook
张开刚刚创立的模子类: application/models/Guestbook.php 并增多以下代码:
// application/models/Guestbook.php
class Application_Model_Guestbook
{
protected $_comment;
protected $_created;
protected $_email;
protected $_id;
public function __construct(array $options = null)
{
if (is_array($options)) {
$this->setOptions($options);
}
}
public function __set($name, $value)
{
$method = 'set' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid guestbook property');
}
$this->$method($value);
}
public function __get($name)
{
$method = 'get' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid guestbook property');
}
return $this->$method();
}
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
public function setComment($text)
{
$this->_comment = (string) $text;
return $this;
}
public function getComment()
{
return $this->_comment;
}
public function setEmail($email)
{
$this->_email = (string) $email;
return $this;
}
public function getEmail()
{
return $this->_email;
}
public function setCreated($ts)
{
$this->_created = $ts;
return $this;
}
public function getCreated()
{
return $this->_created;
}
public function setId($id)
{
$this->_id = (int) $id;
return $this;
}
public function getId()
{
return $this->_id;
}
}
谈到底,大家创立八个 guestbook controller 查询并出示数据库中的结果:
$ zf create controller Guestbook
那将开创 application/controllers/GuestbookController.php,它有三个
IndexAction
方法,同时,在 application/views/scripts/guestbook
目录中开创了三个 index.phtml 文件。
开垦 GuestbookController,在 IndexAction 中增多代码,展现全体的 guestbook 记录:
// application/controllers/GuestbookController.php
class GuestbookController extends Zend_Controller_Action
{
public function indexAction()
{
$guestbook = new Application_Model_GuestbookMapper();
$this->view->entries = $guestbook->fetchAll();
}
}
打开 application/views/scripts/guestbook/index.phtml 增加以下内容:
<!-- application/views/scripts/guestbook/index.phtml -->
<p><a href="<?php echo $this->url(
array(
'controller' => 'guestbook',
'action' => 'sign'
),
'default',
true) ?>">Sign Our Guestbook</a></p>
Guestbook Entries: <br />
<dl>
<?php foreach ($this->entries as $entry): ?>
<dt><?php echo $this->escape($entry->email) ?></dt>
<dd><?php echo $this->escape($entry->comment) ?></dd>
<?php endforeach ?>
</dl>
切换成浏览器,张开:
,你应有见到这一个剧情:
开采未有数量,那就张开phpMyadmin,插入一些多少再看看,复制下边包车型大巴sql语句到phpmyadmin并进行:
INSERT INTO `guestbook`.`guestbook` (`id`, `email`, `comment`, `created`) VALUES (NULL, 'noemail@qq.com', 'good', CURRENT_TIMESTAMP),
(NULL, 'noemail2@qq.com', 'good book', CURRENT_TIMESTAMP),
(NULL, 'noemail3@qq.com', 'good book ok', CURRENT_TIMESTAMP);
刷新浏览器,结果如图所示,成功地从数据库读取数据并出示在页面上:
新建实现之后,张开该CMD,保持该CMD窗口为开采状态,后续就能够趋之若鹜数据库、操作数据库了。
server>controllers 文件夹下边放置的都以接口文件
为了让 guestbook 更有效一些,我们需求七个表单来交给新的评论和介绍项。
第豆蔻梢头,成立一个 form 类:
$ zf create form Guestbook
展开刚创设的 form 类 application/forms/Guestbook.php ,增添下列代码:
// application/forms/Guestbook.php
class Application_Form_Guestbook extends Zend_Form
{
public function init()
{
// Set the method for the display form to POST
$this->setMethod('post');
// Add an email element
$this->addElement('text', 'email', array(
'label' => 'Your email address:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'EmailAddress',
)
));
// Add the comment element
$this->addElement('textarea', 'comment', array(
'label' => 'Please Comment:',
'required' => true,
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));
// Add a captcha
$this->addElement('captcha', 'captcha', array(
'label' => 'Please enter the 5 letters displayed below:',
'required' => true,
'captcha' => array(
'captcha' => 'Figlet',
'wordLen' => 5,
'timeout' => 300
)
));
// Add the submit button
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Sign Guestbook',
));
// And finally add some CSRF protection
$this->addElement('hash', 'csrf', array(
'ignore' => true,
));
}
}
下面代码定义了七个要素:email地址,商量输入框,验证码,提交按键和CSTiggoF爱戴字段。
下一步,添加 signAction
到
GuestbookController
,它用来拍卖表单提交页面。使用 zf 命令创设:
$ zf create action sign Guestbook
创制了 signAction 和对应的 view script.
然后加多一些代码到 signAction,首先检查是否有POST或GET央求,然后若未有就差不离地呈现表单,若有,则注脚提交的多寡,并保留到数据库中
// application/controllers/GuestbookController.php
class GuestbookController extends Zend_Controller_Action
{
// snipping indexAction()...
public function signAction()
{
$request = $this->getRequest();
$form = new Application_Form_Guestbook();
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
$comment = new Application_Model_Guestbook($form->getValues());
$mapper = new Application_Model_GuestbookMapper();
$mapper->save($comment);
return $this->_helper->redirector('index');
}
}
$this->view->form = $form;
}
}
理当如此,还亟需编写制定一下 view application/views/scripts/guestbook/sign.phtml
<!-- application/views/scripts/guestbook/sign.phtml -->
Please use the form below to sign our guestbook!
<?php
$this->form->setAction($this->url());
echo $this->form;
命令行展开项目根目录,推行npm install mongoose --save
安装Mongoose
server>routes 下边包车型客车 index.js 为接口路由
现行反革命再打开浏览器:
看看,效果如下:
填写好表单点击提交,就能够见到列表已经更新了:
注: 上面的验证码部分辨认非常不便,其实要是复制一下粘贴到txt文书档案中就能够看通晓了。
接下去本身将会以叁个todo list来作为实例,向我们批注。有个别剧情本人上篇小说已经聊到过,就相当的少说了,请参见:nodejs之Express入门
你曾经打响地动用 Zend Framework 的常用功用建设布局了叁个粗略的应用程序。Zend Framework 内置了好些个组件,你可以直接用在你的连串中,那个零零器件包罗 web services,寻觅,PDF读取和成立,身份ID明等等。能够在 文书档案参照他事他说加以考查 中找到越来越多相关的技巧细节。
转发请评释来源:
塞尔维亚语原版的书文链接:
在类型文件夹根目录上,新建db.js,内容:
var mongoose = require("mongoose"); //引入mongoose
var db = mongoose.connection;
db.on('error', function callback() { //监听是否有异常
console.log("Connection error");
});
db.once('open', function callback() { //监听一次打开
//在这里创建你的模式和模型
console.log('connected!');
});
mongoose.connect('mongodb://localhost/todo'); //连接到mongoDB的todo数据库
//该地址格式:mongodb://[username:password@]host:port/database[?options]
//默认port为27017
module.exports = mongoose;
在app.js最前面引进,
require('./db');
接下来就足以,npm start
试跳,是还是不是连接成功,记住:这时mongoDB的劳必需必要开发!!连接成功如下图:
1.在controllers 下创建三个demo.js 的文件 输入下边包车型客车代码
大家要求八个Schema和三个Model来将数据保存在MongoDB数据库中。Schema定义了三个聚众中文档的构造,Model被用来创立将在存款和储蓄在文书档案中的数据Entity。Schema生成Model,Model创造Entity,Model和Entity都可对数据库操作产生影响,但Model比Entity更具操作性。
那正是说接下去大家来定义它们,在db.js
中增多底下内容:
var TodoSchema = new mongoose.Schema({
user_id: String, //定义一个属性user_id,类型为String
content: String, //定义一个属性content,类型为String
updated_at: Date //定义一个属性updated_at,类型为Date
});
mongoose.model('Todo', TodoSchema); //将该Schema发布为Model
模型定义好了,以后我们就要起来往数据库增多数据了。
大家用事情发生前小说里的更改的脚手架,起头搭建。这里大家用到的是ejs模板引擎,所以大家要求计划一下:
1 module.exports = ctx => {
2 ctx.state.data = {
3 msg: 'Hello World'
4 }
5 }
命令行输入:npm install ejs-mate --save
var engine = require('ejs-mate');
///======= view engine setup 模板 开始===========//
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('ejs', engine);
///======= view engine setup 模板 结束===========//
如图:
<!DOCTYPE html>
<html>
<head>
<title>
<%= title %>
</title>
<!-- 新 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
<link rel='stylesheet' href='/stylesheets/screen.css' />
</head>
<body>
<div id="layout" class="container-fluid">
<%- body -%> <!--之后我们的内容就会填充再这个里面 -->
</div>
<!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
<script src="http://www.hamupet.com/uploads/allimg/191128/1413553Q1-14.jpg"></script>
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="http://www.hamupet.com/uploads/allimg/191128/141355I62-15.jpg"></script>
</body>
</html>
<% layout('layout') -%> <!-- 用于识别填充到模板中的内容 -->
<div class="row">
<div class="col-xs-12 text-center">
<h1> <%= title %></h1>
</div>
</div>
<div class="row">
<div class="col-xs-12 text-center">
<form action="/create" method="post" accept-charset="utf-8">
<input class="input" type="text" name="content" />
</form>
</div>
</div>
2、打开 index.js
router.post('/create', function(req, res) {
console.log('req.body', req.body);
new TodoModel({ //实例化对象,新建数据
content: req.body.content,
updated_at: Date.now()
}).save(function(err, todo, count) { //保存数据
console.log('内容', todo, '数量', count); //打印保存的数据
res.redirect('/'); //返回首页
});
});
接下来运转服务,npm start
,在页面输入框输入任何内容,回车。
在module.exports = router 前边参加
若出现req.body
为undefined
,请检查app.js
是还是不是引进:
var bodyParser = require('body-parser'); //处理请求body的中间件
是或不是安插:
app.use(bodyParser.urlencoded({ extended: false })); //解析 application/x-www-form-urlencoded类型
app.use(bodyParser.json()); //解析 application/json类型
router定义:
app.use('/', routes); //在app中注册routes该接口
app.use('/users', users); //在app中注册users接口
总得写在布置的末尾。
1 router.get('/demo',controllers.demo)
// 显示所有待办事项
<% todos.forEach( function( todo ){ %>
<div class="row">
<div class="col-xs-2 text-center">
<p>
<%= todo.updated_at %>
</p>
</div>
<div class="col-xs-6 text-center">
<p><%= todo.content %></p>
</div>
<div class="col-xs-4 text-center">
<a href="/destroy/<%= todo._id %>" title="Delete this todo item">Delete</a>
</div>
</div>
<% }); %>
3.更新Tencent云后
router.get('/', function(req, res, next) {
// 查询数据库获取所有待办事项.
TodoModel.find(function(err, todos, count) {
res.render('index', { //渲染页面
title: 'Todo List',
todos: todos
});
});
});
//需要传入参数id
router.get('/destroy/:id', function(req, res) {
//根据待办事项的id 来删除它
TodoModel.findById(req.params.id, function(err, todo) {
todo.remove(function(err, todo) {
res.redirect('/');
});
});
});
张开浏览器输入
落到实处格局是当鼠标点击待办事项时,页面转向edit页面,将待办事项转化为input text标签。
//跳转到编辑页面
router.get('/edit/:id', function(req, res) {
TodoModel.find(function(err, todos, count) {
res.render('edit', { //重新渲染页面
title: 'Todo List',
todos: todos,
current: req.params.id
});
});
});
//根据传入的数据id,更改数据
router.post('/update/:id', function(req, res) {
TodoModel.findById(req.params.id, function(err, todo) {
todo.content = req.body.content;
todo.updated_at = Date.now();
todo.save(function(err, todo, count) {
res.redirect('/');
});
});
});
更新后浏览器呈现
//省略与index.ejs相同部分;主要修改以下内容
<% todos.forEach( function( todo ){ %>
<div class="row">
<div class="col-xs-2 text-center">
<p><%= todo.updated_at %></p>
</div>
<div class="col-xs-6 text-center">
<% if( todo._id == current ){ %>
<form action="/update/<%= todo._id %>" method="post" accept-charset="utf-8">
<input type="text" name="content" value="<%= todo.content %>" />
</form>
<% }else{ %>
<a href="/edit/<%= todo._id %>" title="Update this todo item"><%= todo.content %></a>
<% } %>
</div>
<div class="col-xs-2 text-center">
<a href="/edit/<%= todo._id %>" title="Edit this todo item">Edit</a>
</div>
<div class="col-xs-2 text-center">
<a href="/destroy/<%= todo._id %>" title="Delete this todo item">Delete</a>
</div>
</div>
<% }); %>
<% todos.forEach( function( todo ){ %>
<div class="row">
<div class="col-xs-2 text-center">
<p>
<%= todo.updated_at %>
</p>
</div>
<div class="col-xs-6 text-center">
<p>
<%= todo.content %>
</p>
</div>
<div class="col-xs-2 text-center">
<a href="/edit/<%= todo._id %>" title="Edit this todo item">Edit</a>
</div>
<div class="col-xs-2 text-center">
<a href="/destroy/<%= todo._id %>" title="Delete this todo item">Delete</a>
</div>
</div>
<% }); %>
到此处Todo list基本效率已经成功了,上面我们再增多贰个排序功能。
三、链接MySql
让待办事项改过时间各样进行排序。
在 demo.js加多如下代码
router.get('/', function(req, res, next) {
// 查询数据库获取所有待办事项.
TodoModel.
find().
sort('uadated_at').
(function(err, todos, count) {
res.render('index', { //渲染页面
title: 'Todo List',
todos: todos
});
});
});
//跳转到编辑页面
router.get('/edit/:id', function(req, res) {
TodoModel.
find().
sort('uadated_at').
(function(err, todos, count) {
res.render('edit', { //重新渲染页面
title: 'Todo List',
todos: todos,
current: req.params.id
});
});
});
源码已经上盛传Github上了,为了美貌使用bootstrap简单的改变了刹那间,其余内容都未有更改。
(end)
1 const { mysql } = require('../qcloud')
2
3 module.exports = async ctx => {
4 var result = await mysql('user')
5 ctx.state.data = {
6 msg: result
7 }
8 }
更新腾讯云后访谈浏览器就能够得到你想要的数量了
如图
更多多少操作,knex.js 精晓一下
附上自个儿的demo.js
1 // 官网 Demo
2 // module.exports = ctx => {
3 // ctx.state.data = {
4 // msg: 'Hello World'
5 // }
6 // }
7
8 const { mysql } = require('../qcloud')
9
10 module.exports = async ctx => {
11 var result = await mysql('user')
12 //sql:select * from `user`
13 ctx.state.data = {
14 msg: result
15 }
16 }
17 // =======================================================================================
18 // select
19 // 显示指定字段:var result = await mysql.select('name', 'id').from('user')
20 // sql:selece 'name', 'id' from `user`;
21
22 // 条件查询:var result = await mysql.select('id','name','openid' ).from('user').where('id',2)
23 // sql: select 'id','name','openid' form `user` where id=2;
24
25 // =======================================================================================
26 // update
27 // var result = await mysql('user').update({ name: 'root', openid: 'xubde724xie=395' }).where('id', 2)
28 // sql:update `user` set name='root', openid='xubde724xie=395' where id=2;
29
30 // =======================================================================================
31 // delete
32 // var result = await mysql('user').del().where('id', 3)
33 // sql:delete from `user` where id=3
34
35 // =======================================================================================
36 // insect
37 // var result = await mysql.insert({ name: 'cain' }, { openid: 'Ux6892Drfixbx'}).into('user')
38 // var result = await mysql('user').insert({ name: 'cain', openid: 'Ux6892Drfixbx' })
39 // sql: insert into `user` (`name`, `openid`) values (`cain`, `Ux6892Drfixbx`)
40 // 两种均可
41 // 会返回插入条目id序号 注意传入的数据类型与表字段的数据类型不符不会报错
【版权申明】转发请申明出处:
本文由星彩网app下载发布于星彩彩票app下载,转载请注明出处:小程序连接MySql数据库