1+ <?php
2+
3+ namespace PFinal \Database ;
4+
5+ class ActiveRecord extends Builder
6+ {
7+ public function __construct (array $ config = array ())
8+ {
9+ parent ::__construct ($ config );
10+
11+ if (static ::$ modelStorage === null ) {
12+ static ::$ modelStorage = new \SplObjectStorage ();
13+ }
14+ $ this ->table (static ::tableName ());
15+ }
16+
17+ public static function tableName ()
18+ {
19+ $ name = get_called_class ();
20+
21+ //去掉namespace
22+ $ name = rtrim (str_replace ('\\' , '/ ' , $ name ), '/ \\' );
23+ if (($ pos = mb_strrpos ($ name , '/ ' )) !== false ) {
24+ $ name = mb_substr ($ name , $ pos + 1 );
25+ }
26+
27+ //大写转为下划线风格
28+ return trim (strtolower (preg_replace ('/[A-Z]/ ' , '_\0 ' , $ name )), '_ ' );
29+ }
30+
31+ /**
32+ * @param Connection $db
33+ * @return static
34+ */
35+ public static function find ($ db )
36+ {
37+ $ model = new static ;
38+ return $ model ->setConnection ($ db )->asEntity (get_called_class ());
39+ }
40+
41+ public function one ()
42+ {
43+ return parent ::findOne ();
44+ }
45+
46+ public function all ()
47+ {
48+ return parent ::findAll ();
49+ }
50+
51+ /**
52+ * @var \SplObjectStorage
53+ */
54+ protected static $ modelStorage = null ;
55+
56+ public function findAllBySql ($ sql = '' , $ params = array (), $ fetchClass = null )
57+ {
58+ if ($ fetchClass === null ) {
59+ return parent ::findAllBySql ($ sql , $ params , $ fetchClass );
60+ } else {
61+
62+ $ models = parent ::findAllBySql ($ sql , $ params , $ fetchClass );
63+
64+ array_walk ($ models , function (&$ model ) {
65+ static ::$ modelStorage ->attach ($ model , serialize ((array )$ model ));
66+ });
67+
68+ return $ models ;
69+ }
70+ }
71+
72+ public function isNewRecord ()
73+ {
74+ return !static ::$ modelStorage ->contains ($ this );
75+ }
76+
77+ /**
78+ * @return bool
79+ */
80+ public function save ()
81+ {
82+ if ($ this ->isNewRecord ()) {
83+ if (($ id = $ this ->insertGetId ((array )$ this )) > 0 ) {
84+ $ this ->id = $ id ;//todo pk
85+ return true ;
86+ }
87+ return false ;
88+ } else {
89+
90+ $ pk = static ::$ modelStorage ->offsetGet ($ this );
91+
92+ return 1 == $ this ->where ('id=? ' , array ($ pk ))->update ((array )$ this );//todo pk
93+ }
94+ }
95+ }
0 commit comments