热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

PHPPDO_MYSQL操作类YAF嵌入高性能类而准备

https:github.comindieteqPHP-MySQL-PDO-Database-ClassPHP-PDO-MySQL-ClassAPHPMySQLPDOclasssi

https://github.com/indieteq/PHP-MySQL-PDO-Database-Class

PHP-PDO-MySQL-Class
A PHP MySQL PDO
class similar to the the Python MySQLdb.
Initialize
php
define(DBHost, 127.0.0.1);
define(
DBName, Database);
define(
DBUser, root);
define(
DBPassword, ‘‘);
require(dirname(__FILE__).
"/src/PDO.class.php");
$DB
= new Db(DBHost, DBName, DBUser, DBPassword);
?>
Preventing SQL Injection Attacks
Safety: Use parameter binding method
Safety Example:
php
$DB->query("SELECT * FROM fruit WHERE name=?", array($_GET[name]));
?>
Unsafety: Split joint SQL
string
Unsafety Example:
php
$DB->query("SELECT * FROM fruit WHERE name=".$_GET[name]);
?>
Usage
table
"fruit"
id name color
1 apple red
2 banana yellow
3 watermelon green
4 pear yellow
5 strawberry red
Fetching with Bindings (ANTI
-SQL-INJECTION):
php
$DB->query("SELECT * FROM fruit WHERE name=? and color=?",array(apple,red));
$DB
->query("SELECT * FROM fruit WHERE name=:name and color=:color",array(name=>apple,color=>red));
?>
Result:
Array
(
[
0] => Array
(
[id]
=> 1
[name]
=> apple
[color]
=> red
)
)
WHERE IN:
php
$DB->query("SELECT * FROM fruit WHERE name IN (?)",array(apple,banana));
?>
Result:
Array
(
[
0] => Array
(
[id]
=> 1
[name]
=> apple
[color]
=> red
)
[
1] => Array
(
[id]
=> 2
[name]
=> banana
[color]
=> yellow
)
)
Fetching Column:
php
$DB->column("SELECT color FROM fruit WHERE name IN (?)",array(apple,banana,watermelon));
?>
Result:
Array
(
[
0] => red
[
1] => yellow
[
2] => green
)
Fetching Row:
php
$DB->row("SELECT * FROM fruit WHERE name=? and color=?",array(apple,red));
?>
Result:
Array
(
[id]
=> 1
[name]
=> apple
[color]
=> red
)
Fetching single:
php
$DB->single("SELECT color FROM fruit WHERE name=? ",array(watermelon));
?>
Result:
green
Delete
/ Update / Insert
These operations will
return the number of affected result set. (integer)
php
// Delete
$DB->query("DELETE FROM fruit WHERE id = :id", array("id"=>"1"));
$DB
->query("DELETE FROM fruit WHERE id = ?", array("1"));
// Update
$DB->query("UPDATE fruit SET color = :color WHERE name = :name", array("name"=>"strawberry","color"=>"yellow"));
$DB
->query("UPDATE fruit SET color = ? WHERE name = ?", array("yellow","strawberry"));
// Insert
$DB->query("INSERT INTO fruit(id,name,color) VALUES(?,?,?)", array(null,"mango","yellow"));//Parameters must be ordered
$DB->query("INSERT INTO fruit(id,name,color) VALUES(:id,:name,:color)", array("color"=>"yellow","name"=>"mango","id"=>null));//Parameters order free
?>
Get Last Insert ID
php
$DB->lastInsertId();
?>
Get the number of queries since the
object initialization
php
$DB->querycount;
?>
Close Connection
php
$DB->CloseConnection;
?>

 

 

 

https://github.com/fightbulc/simplon_mysql

 

Dependecies
PHP
>= 5.3
PDO
1. Installing
Easy install via composer. Still no idea what composer
is? Inform yourself here.
{
"require": {
"simplon/mysql": "*"
}
}
2. Direct vs. SqlManager
I implemented two different ways of interacting with MySQL. The first option
is the usual one which interacts directly with the database. Following a straight forward example to show you what I mean:
$dbConn
->fetchRow(SELECT * FROM names WHERE name = :name, array(name => Peter));
In constrast to the prior method the SqlManager uses a Builder Pattern to deal with the database. What advantage does that offer
? Well, in case that we want to do more things with our query before sending it off we encapsule it as a Builder Pattern. From there on we could pass it throughout our application to add more data or alike before sending the query finally off to the database. Again, a quick example of how we would rewrite the above direct query:
$sqlBuilder
= new \Simplon\Mysql\Manager\SqlQueryBuilder();
$sqlBuilder
->setQuery(SELECT * FROM names WHERE name = :name)
->setConditions(array(name => Peter));
$sqlManager
= new \Simplon\Mysql\Manager\SqlManager($dbConn);
$sqlManager
->fetchRow($sqlBuilder);
3. Setup connection
The library requires a config value
object in order to instantiate a connection with MySQL. See how its done:

$config
= array(
// required credentials
host => localhost,
user => rootuser,
password => rootuser,
database => our_database,
// optional
fetchMode => \PDO::FETCH_ASSOC,
charset => utf8,
port => 3306,
unixSocket => null,
);
// standard setup
$dbCOnn= new \Simplon\Mysql\Mysql(
$config[
host],
$config[
user],
$config[
password],
$config[
database]
);
The following code shows all possible parameters to setup a connection:
\Simplon\Mysql\Mysql::__construct(
$host,
$user,
$password,
$database,
$fetchMode
= \PDO::FETCH_ASSOC,
$charset
= utf8,
array $options
= array(port => 3306, unixSocket => ‘‘)
);
In
case that you wanna use the SqlManager there is one piece missing:
$sqlManager
= new \Simplon\Mysql\Manager\SqlManager($dbConn);
4. Usage: Direct access
4.1. Query
FetchColumn
Returns a selected column
from the first match. The example below returns id or null if nothing was found.
$result
= $dbConn->fetchColumn(SELECT id FROM names WHERE name = :name, array(name => Peter));
// result
var_dump($result); // ‘1‘ || null
FetchColumnMany
Returns an array with the selected column
from all matching datasets. In the example below an array with all ids will be returned or null if nothing was found.
$result
= $dbConn->fetchColumnMany(SELECT id FROM names WHERE name = :name, array(name => Peter));
// result
var_dump($result); // [‘1‘, ‘15‘, ‘30‘, ...] || null
FetchColumnManyCursor
Returns one matching dataset at a time. It
is resource efficient and therefore handy when your result has many data. In the example below you either iterate through the foreach loop in case you have matchings or nothing will happen.
$cursor
= $dbConn->fetchColumnMany(SELECT id FROM names WHERE name = :name, array(name => Peter));
foreach ($cursor as $result)
{
var_dump($result);
// ‘1‘
}
FetchRow
Returns all selected columns
from a matched dataset. The example below returns id, age for the matched dataset. If nothing got matched null will be returned.
$result
= $dbConn->fetchRow(SELECT id, age FROM names WHERE name = :name, array(name => Peter));
var_dump($result);
// [‘id‘ => ‘1‘, ‘age‘ => ‘22‘] || null
FetchRowMany
Returns all selected columns
from all matched dataset. The example below returns for each matched dataset id, age. If nothing got matched null will be returned.
$result
= $dbConn->fetchRowMany(SELECT id, age FROM names WHERE name = :name, array(name => Peter));
var_dump($result);
// [ [‘id‘ => ‘1‘, ‘age‘ => ‘22‘], [‘id‘ => ‘15‘, ‘age‘ => ‘40‘], ... ] || null
FetchRowManyCursor
Same explanation
as for FetchColumnManyCursor except that we receive all selected columns.
$result
= $dbConn->fetchRowMany(SELECT id, age FROM names WHERE name = :name, array(name => Peter));
foreach ($cursor as $result)
{
var_dump($result);
// [‘id‘ => ‘1‘, ‘age‘ => ‘22‘]
}
4.2. Insert
Single data
Inserting data into the database
is pretty straight forward. Follow the example below:
$data
= array(
id => false,
name => Peter,
age => 45,
);
$id
= $dbConn->insert(names, $data);
var_dump($id);
// 50 || bool
The result depends on the table. If the table holds an autoincrementing ID column you will receive the ID count for the inserted data. If the table does not hold such a field you will receive true for a successful insert. If anything went bogus you will receive false.
Many datasets
Follow the example
for inserting many datasets at once:
$data
= array(
array(
id => false,
name => Peter,
age => 45,
),
array(
id => false,
name => Peter,
age => 16,
),
);
$id
= $dbConn->insertMany(names, $data);
var_dump($id);
// 50 || bool
The result depends on the table. If the table holds an autoincrementing ID column you will receive the ID count for the inserted data. If the table does not hold such a field you will receive true for a successful insert. If anything went bogus you will receive false.
4.3. Updating
Simple update statement
Same
as for insert statements accounts for updates. Its easy to understand. If the update succeeded the response will be true. If nothing has been updated you will receive null.
$conds
= array(
id => 50,
);
$data
= array(
name => Peter,
age => 50,
);
$result
= $dbConn->update(names, $conds, $data);
var_dump($result);
// true || null
Custom update conditions query
Same
as for insert statements accounts for updates. Its easy to understand. If the update succeeded the response will be true. If nothing has been updated you will receive null.
$conds
= array(
id => 50,
name => Peter,
);
// custom conditions query
$cOndsQuery= id = :id OR name =: name;
$data
= array(
name => Peter,
age => 50,
);
$result
= $dbConn->update(names, $conds, $data, $condsQuery);
var_dump($result);
// true || null
4.4. Replace
As MySQL states it: REPLACE works exactly like INSERT, except that
if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
Replace a single datasets
As a result you will either receive the INSERT ID or
false in case something went wrong.
$data
= array(
id => 5,
name => Peter,
age => 16,
);
$result
= $dbConn->replace(names, $data);
var_dump($result);
// 1 || false
Replace multiple datasets
As a result you will either receive an array of INSERT IDs or
false in case something went wrong.
$data
= array(
array(
id => 5,
name => Peter,
age => 16,
),
array(
id => 10,
name => John,
age => 22,
),
);
$result
= $dbConn->replaceMany(names, $data);
var_dump($result);
// [5, 10] || false
4.5. Delete
Simple delete conditions
The following example demonstrates how to remove data. If the query succeeds we will receive
true else false.
$result
= $dbConn->delete(names, array(id => 50));
var_dump($result);
// true || false
Custom delete conditions query
The following example demonstrates how to remove data with a custom conditions query. If the query succeeds we will receive
true else false.
$conds
= array(
id => 50,
name => John,
);
// custom conditions query
$cOndsQuery= id = :id OR name =: name;
$result
= $dbConn->delete(names, $conds, $condsQuery);
var_dump($result);
// true || false
4.6. Execute
This method
is ment for calls which do not require any parameters such as TRUNCATE. If the call succeeds you will receive true. If it fails an MysqlException will be thrown.
$result
= $dbConn->executeSql(TRUNCATE names);
var_dump($result);
// true
5. Usage: SqlManager
The following query examples will be a rewrite of the aforementioned direct access examples. Remember: We need an instance of the SqlManager. Paragraph
3. Setup connection shows how to get your hands on it.
5.1. Query
FetchColumn
Returns a selected column
from the first match. In the example below id will be returned or null if nothing was found.
$sqlBuilder
= new \Simplon\Mysql\Manager\SqlQueryBuilder();
$sqlBuilder
->setQuery(SELECT id FROM names WHERE name = :name)
->setConditions(array(name => Peter));
$result
= $sqlManager->fetchColumn($sqlBuilder);
// result
var_dump($result); // ‘1‘ || null
FetchColumnMany
Returns an array with the selected column
from all matching datasets. In the example below an array with all ids will be returned or null if nothing was found.
$sqlBuilder
= new \Simplon\Mysql\Manager\SqlQueryBuilder();
$sqlBuilder
->setQuery(SELECT id FROM names WHERE name = :name)
->setConditions(array(name => Peter));
$result
= $sqlManager->fetchColumnMany($sqlBuilder);
// result
var_dump($result); // [‘1‘, ‘15‘, ‘30‘, ...] || null
FetchColumnManyCursor
Returns one matching dataset at a time. It
is resource efficient and therefore handy when your result has many data. In the example below you either iterate through the foreach loop in case you have matchings or nothing will happen.
$sqlBuilder
= new \Simplon\Mysql\Manager\SqlQueryBuilder();
$sqlBuilder
->setQuery(SELECT id FROM names WHERE name = :name)
->setConditions(array(name => Peter));
foreach ($sqlManager->fetchColumnMany($sqlBuilder) as $result)
{
var_dump($result);
// ‘1‘
}
FetchRow
Returns all selected columns
from a matched dataset. The example below returns id, age for the matched dataset. If nothing got matched null will be returned.
$sqlBuilder
= new \Simplon\Mysql\Manager\SqlQueryBuilder();
$sqlBuilder
->setQuery(SELECT id, age FROM names WHERE name = :name)
->setConditions(array(name => Peter));
$result
= $sqlManager->fetchRow($sqlBuilder);
var_dump($result);
// [‘id‘ => ‘1‘, ‘age‘ => ‘22‘] || null
FetchRowMany
Returns all selected columns
from all matched dataset. The example below returns for each matched dataset id, age. If nothing got matched null will be returned.
$sqlBuilder
= new \Simplon\Mysql\Manager\SqlQueryBuilder();
$sqlBuilder
->setQuery(SELECT id, age FROM names WHERE name = :name)
->setConditions(array(name => Peter));
$result
= $sqlManager->fetchRowMany($sqlBuilder);
var_dump($result);
// [ [‘id‘ => ‘1‘, ‘age‘ => ‘22‘], [‘id‘ => ‘15‘, ‘age‘ => ‘40‘], ... ] || null
FetchRowManyCursor
Same explanation
as for FetchColumnManyCursor except that we receive all selected columns.
$sqlBuilder
= new \Simplon\Mysql\Manager\SqlQueryBuilder();
$sqlBuilder
->setQuery(SELECT id, age FROM names WHERE name = :name)
->setConditions(array(name => Peter));
foreach ($sqlManager->fetchRowManyCursor($sqlBuilder) as $result)
{
var_dump($result);
// [‘id‘ => ‘1‘, ‘age‘ => ‘22‘]
}
5.2. Insert
Single data
Inserting data into the database
is pretty straight forward. Follow the example below:
$data
= array(
id => false,
name => Peter,
age => 45,
);
$sqlBuilder
= new \Simplon\Mysql\Manager\SqlQueryBuilder();
$sqlBuilder
->setTableName(names)
->setData($data);
$id
= $sqlManager->insert($sqlBuilder);
var_dump($id);
// 50 || false
The result depends on the table. If the table holds an autoincrementing ID column you will receive the ID count for the inserted data. If the table does not hold such a field you will receive true for a successful insert. If anything went bogus you will receive false.
Many datasets
Follow the example
for inserting many datasets at once:
$data
= array(
array(
id => false,
name => Peter,
age => 45,
),
array(
id => false,
name => Peter,
age => 16,
),
);
$sqlBuilder
= (new \Simplon\Mysql\Manager\SqlQueryBuilder())
->setTableName(names)
->setData($data);
$result
= $sqlManager->insert($sqlBuilder);
var_dump($id);
// [50, 51, ...] || false
The result depends on the table. If the table holds an autoincrementing ID column you will receive the ID count for the inserted data. If the table does not hold such a field you will receive true for a successful insert. If anything went bogus you will receive false.
5.3. Update
Simple update statement
Same
as for insert statements accounts for updates. Its easy to understand. If the update succeeded the response will be true. If nothing has been updated you will receive null.
$data
= array(
name => Peter,
age => 50,
);
$sqlBuilder
= new \Simplon\Mysql\Manager\SqlQueryBuilder();
$sqlBuilder
->setTableName(names)
->setConditions(array(id => 50))
->setData($data);
$result
= $sqlManager->update($sqlBuilder);
var_dump($result);
// true || null
Custom update conditions query
Same
as for insert statements accounts for updates. Its easy to understand. If the update succeeded the response will be true. If nothing has been updated you will receive null.
$data
= array(
name => Peter,
age => 50,
);
$sqlBuilder
= new \Simplon\Mysql\Manager\SqlQueryBuilder();
$sqlBuilder
->setTableName(names)
->setConditions(array(id => 50))
->setConditionsQuery(id = :id OR name =: name)
->setData($data)
$result
= $sqlManager->update($sqlBuilder);
var_dump($result);
// true || null
5.4. Replace
As MySQL states it: REPLACE works exactly like INSERT, except that
if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
Replace a single datasets
As a result you will either receive the INSERT ID or
false in case something went wrong.
$data
= array(
id => 5,
name => Peter,
age => 16,
);
$sqlBuilder
= new \Simplon\Mysql\Manager\SqlQueryBuilder();
$sqlBuilder
->setTableName(names)
->setData($data);
$result
= $sqlManager->replace($sqlBuilder);
var_dump($result);
// 1 || false
Replace multiple datasets
As a result you will either receive an array of INSERT IDs or
false in case something went wrong.
$data
= array(
array(
id => 5,
name => Peter,
age => 16,
),
array(
id => 10,
name => John,
age => 22,
),
);
$sqlBuilder
= new \Simplon\Mysql\Manager\SqlQueryBuilder();
$sqlBuilder
->setTableName(names)
->setData($data);
$result
= $sqlManager->replaceMany($sqlBuilder);
var_dump($result);
// [5, 10] || false
5.5. Delete
Simple delete conditions
The following example demonstrates how to remove data. If the query succeeds we will receive
true else false.
$sqlBuilder
= new \Simplon\Mysql\Manager\SqlQueryBuilder();
$sqlBuilder
->setTableName(names)
->setConditions(array(id => 50));
$result
= $sqlManager->delete($sqlBuilder);
var_dump($result);
// true || false
Custom delete conditions query
The following example demonstrates how to remove data with a custom conditions query. If the query succeeds we will receive
true else false.
$sqlBuilder
= new \Simplon\Mysql\Manager\SqlQueryBuilder();
$sqlBuilder
->setTableName(names)
->setConditions(array(id => 50, name => Peter))
->setConditionsQuery(id = :id OR name =: name);
$result
= $sqlManager->delete($sqlBuilder);
var_dump($result);
// true || false
6. IN() Clause Handling
6.1. The issue
There
is no way using an IN() clause via PDO. This functionality is simply not given. However, you could do something like the following:
$ids
= array(1,2,3,4,5);
$query
= "SELECT * FROM users WHERE id IN (" . join(,, $ids) . ")";
Looks good at first sight
- not sexy but probably does the job, right? Wrong. This approach only works with INTEGERS and it does not ESCAPE the users input - the reason why we use PDO in first place.

Just
for the record here is a string example which would not work:
$emails
= array(johnny@me.com, peter@ibm.com);
$query
= "SELECT * FROM users WHERE email IN (" . join(,, $emails) . ")";
The only way how
this would work is by wrapping each value like the following: "email". Way too much work.
6.2. The solution
To take advantage of the built
in IN() Clause with escaping and type handling do the following:
// integers
$cOnds= array(ids => array(1,2,3,4,5));
$query
= "SELECT * FROM users WHERE id IN (:ids)";
// strings
$cOnds= array(emails => array(johnny@me.com, peter@ibm.com));
$query
= "SELECT * FROM users WHERE email IN (:emails)";
7. CRUD Helper (CONTENT IS OUTDATED. UPDATE WILL FOLLLOW)
7.1. Intro
CRUD stands
for Create Read Update Delete and reflects the for basic functions for persisent storage.
I found myself writing more and more CRUDs
for all my object/database interactions simply for the reason of having a SINGLE POINT OF ACCESS when I was interacting with these objects for above mentioned functions. Eventually, it has sort of a touch of a database model but with more flexibility. Also, we keep writing VALUE OBJECTS and by that we keep the red line for all our code base.
Note: VALUE OBJECTS are actually MODELS
while models are not value objects. The reason for this is that a value object is vehicle for all sorts of data while models are only vehicles for database data. At least thats what it should be.
7.2. Requirements/Restrictions
There are really not many requirements
/restrictions:
Instance of SqlCrudManager
- requires an instance of Simplon\Mysql.
Value
object needs to extend from SqlCrudVo
Table name should be
in plural or set it via SqlCrudVo::$crudSource within the value object.
Value
objects instance variables must match the tables column names in CamelCase (see example below).
Each value
object reflects ONE OBJECT only - Mysql::fetchRow() fetches your data.
VARIABLE
= COLUMN Dont set any property in your value object which doesnt reflect your database table. If you have to, make either use of SqlCrudVo::crudColumns() or SqlCrudVo::crudIgnore(). See Flexibility for description.
7.3. Flexibility
Set source: In
case you have a table name which cant be easily pluralised (e.g. person/people) you can set the source yourself via SqlCrudVo::$crudSource within value object

Set custom read query: In
case you need a custom query to get your object you can set it when you instantiate the object new SqlCrudVo($query) or simply within your __construct() { parent::construct($query); }.
Callbacks: You can implement two methods which will be called prior
/after saving an object: SqlCrudVo::crudBeforeSave($isCreateEvent) and SqlCrudVo::crudAfterSave($isCreateEvent). The manager will pass you a boolean to let you know what type of save process happens/happened. You could use this e.g. to set automatically created_at and updated_at fields.
Set columns: If you have to either match property
- and column name or only want a selection of your properties make use of SqlCrudVo::crudColumns() within your value object. It should return an array where the ARRAY KEY reflects the value objects VARIABLE NAME and the ARRAY VALUE the COLUMN NAME. Example: array(createdAt => created_at)

Ignore properties: Considering the prior point you could
do the reverse and simply IGNORE VARIABLES. For that implement SqlCrudVo::crudIgnore() which should return an array of properties you would like to ignore.
No assumptions: There are no assumptions about primary keys or anything alike. You
set all conditions for reading, updating and/or deleting objects.
Casted values: Thanks to your value
object which is always in between you and your database you can cast all values - good bye STRING CASTED ONLY values.
7.4. Conclusion
That
s all what is needed - at least for now. Its simple, explicit and flexible enough not to restrict you in your requirements respectively your creativity.
7.5. Examples
Enough talk, bring it on
! Alright, what is needed? Lets assume we have a database table called users and a value object called UserVo. Note: the value object name has to be the singular of the tables plural name.

Here
is the table schema:
CREATE TABLE `users` (
`id`
int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(
50) NOT NULL DEFAULT ‘‘,
`email` varchar(
254) NOT NULL DEFAULT ‘‘,
`created_at`
int(10) unsigned NOT NULL,
`updated_at`
int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE
=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
... and here
is our value object for the given table:
class UserVo extends \Simplon\Mysql\Crud\SqlCrudVo
{
protected $id;
protected $name;
protected $email;
protected $createdAt;
protected $updatedAt;
// ... here goes getter/setter for the above variables
}
Now, lets
do some CRUD, baby! For all processes we need an instance of our SqlCrudManager:
/**
* construct it with an instance of your simplon/mysql
*/
$sqlCrudManager
= new \Simplon\Mysql\Crud\SqlCrudManager($mysqlInstance);
Create a user:
$userVo
= new UserVo();
$userVo
->setId(null)
->setName(Johnny Foobar)
->setEmail(foo@bar.com);
/** @var UserVo $userVo */
$userVo
= $sqlCrudManager->create($userVo);
// print insert id
echo $userVo->getId(); // 1
Read a user:
// conditions: where id = 1
$cOnds= array(id => 1);
/** @var UserVo $userVo */
$userVo
= $sqlCrudManager->read(new UserVo(), $conds);
// print name
echo $userVo->getName(); // Johnny Foobar
Update a user:
// conditions: where id = 1
$cOnds= array(id => 1);
/** @var UserVo $userVo */
$userVo
= $sqlCrudManager->read(new UserVo(), $conds);
// set new name
$userVo->setName(Hansi Hinterseher);
// update
/*
* @var UserVo $userVo */
$userVo
= $sqlCrudManager->update($userVo, $conds);
// print name
echo $userVo->getName(); // Hansi Hinterseher
Delete a user:
// conditions: where id = 1
$cOnds= array(id => 1);
/**
* UserVo::crudGetSource() is the name of the table
* based on the value object‘s name
*/
$sqlCrudManager
->update(UserVo::crudGetSource(), $conds);
7.6. Example Custom Vo
Setting a custom table name since the plural
from person is not persons:
class PersonVo extends \Simplon\Mysql\Crud\SqlCrudVo
{
/**
* @return string
*/
public static function crudGetSource()
{
return people;
}
// ... here goes the rest
}
In
case your column names are totally off there is a way to match them anyway against your properties:
class UserVo extends \Simplon\Mysql\Crud\SqlCrudVo
{
protected $id;
protected $name;
protected $email;
protected $createdAt;
protected $updatedAt;
/**
* @return array
*/
public function crudColumns()
{
return array(
id => xx_id,
name => xx_name,
email => xx_email,
createdAt => xx_created_at,
updatedAt => xx_updated_at,
);
}
// ... here goes the rest
}
Sometimes there are some helper properties which are not part of your database entry. Here
is a way to ignore them:
class UserVo extends \Simplon\Mysql\Crud\SqlCrudVo
{
protected $id;
protected $name;
protected $email;
protected $createdAt;
protected $updatedAt;
// helper property: not part of the people table
protected $isOffline;
/**
* @return array
*/
public function crudIgnore()
{
return array(
isOffline,
);
}
// ... here goes the rest
}
8. Exceptions
For both access methods (direct, sqlmanager) occuring exceptions will be wrapped by a MysqlException. All essential exception information will be summarised
as JSON within the Exception Message.
Here
is an example of how that might look like:
{
"query":"SELECT pro_id FROM names WHERE connector_type = :connectorType","params":{"connectorType":"FB"},"errorInfo":{"sqlStateCode":"42S22","code":1054,"message":"Unknown column ‘pro_id‘ in ‘field list‘"}}
License
Simplon
/Mysql is freely distributable under the terms of the MIT license.
Copyright (c)
2015 Tino Ehrich (tino@bigpun.me)
Permission
is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and
this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED
"AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 


推荐阅读
  • 本文内容为asp.net微信公众平台开发的目录汇总,包括数据库设计、多层架构框架搭建和入口实现、微信消息封装及反射赋值、关注事件、用户记录、回复文本消息、图文消息、服务搭建(接入)、自定义菜单等。同时提供了示例代码和相关的后台管理功能。内容涵盖了多个方面,适合综合运用。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 本文讲述了作者通过点火测试男友的性格和承受能力,以考验婚姻问题。作者故意不安慰男友并再次点火,观察他的反应。这个行为是善意的玩人,旨在了解男友的性格和避免婚姻问题。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • EPICS Archiver Appliance存储waveform记录的尝试及资源需求分析
    本文介绍了EPICS Archiver Appliance存储waveform记录的尝试过程,并分析了其所需的资源容量。通过解决错误提示和调整内存大小,成功存储了波形数据。然后,讨论了储存环逐束团信号的意义,以及通过记录多圈的束团信号进行参数分析的可能性。波形数据的存储需求巨大,每天需要近250G,一年需要90T。然而,储存环逐束团信号具有重要意义,可以揭示出每个束团的纵向振荡频率和模式。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
author-avatar
昕谊凡
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有